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

后端 未结 14 1886
离开以前
离开以前 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
    慢半拍i (楼主)
    2020-11-22 02:51

    edit: I've created a jsPerf.com testcase to compare the accepted answer with my version. Turns out that my version is faster, especially when you go very deep.

    http://jsfiddle.net/9YMm8/

    var nestedObjectAssignmentFor = function(obj, propString, value) {
        var propNames = propString.split('.'),
            propLength = propNames.length-1,
            tmpObj = obj;
    
        for (var i = 0; i <= propLength ; i++) {
            tmpObj = tmpObj[propNames[i]] = i !== propLength ?  {} : value;  
        }
        return obj;
    }
    
    var obj = nestedObjectAssignment({},"foo.bar.foobar","hello world");
    

提交回复
热议问题