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

后端 未结 14 1894
离开以前
离开以前 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:00

    A very straightforward one.

    No recursions or callbacks overhead.

    function setDeepVal(obj, path, val) {
      var props = path.split('.');
      for (var i = 0, n = props.length - 1; i < n; ++i) {
        obj = obj[props[i]] = obj[props[i]] || {};
      }
      obj[props[i]] = val;
      return obj;
    }
    
    
    
    // TEST
    var obj = { hello : 'world' };
    setDeepVal(obj, 'foo.bar.baz', 1);
    setDeepVal(obj, 'foo.bar2.baz2', 2);
    console.log(obj);

提交回复
热议问题