How to set object property (of object property of..) given its string name in JavaScript?

后端 未结 14 1884
离开以前
离开以前 2020-11-22 02:20

Suppose we are only given

var obj = {};
var propName = \"foo.bar.foobar\";

How can we set the prop

14条回答
  •  你的背包
    2020-11-22 03:01

    Here's a simple method that uses a scoped Object that recursively set's the correct prop by path.

    function setObjectValueByPath(pathScope, value, obj) {
      const pathStrings = pathScope.split('/');
      obj[pathStrings[0]] = pathStrings.length > 1 ?
        setObjectValueByPath(
          pathStrings.splice(1, pathStrings.length).join('/'),
          value,
          obj[pathStrings[0]]
        ) :
        value;
      return obj;
    }
    

提交回复
热议问题