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

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

Suppose we are only given

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

How can we set the prop

14条回答
  •  梦毁少年i
    2020-11-22 02:53

    You could split the path and make a check if the following element exist. If not assign an object to the new property.

    Return then the value of the property.

    At the end assign the value.

    function setValue(object, path, value) {
        var fullPath = path.split('.'),
            way = fullPath.slice(),
            last = way.pop();
    
        way.reduce(function (r, a) {
            return r[a] = r[a] || {};
        }, object)[last] = value;
    }
    
    var object = {},
        propName = 'foo.bar.foobar',
        value = 'hello world';
    
    setValue(object, propName, value);
    console.log(object);

提交回复
热议问题