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

后端 未结 14 2046
离开以前
离开以前 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 02:59

    Here is a simple function to do that using reference.

        function setValueByPath (obj, path, value) {
            var ref = obj;
    
            path.split('.').forEach(function (key, index, arr) {
                ref = ref[key] = index === arr.length - 1 ? value : {};
            });
    
            return obj;
        }
    

提交回复
热议问题