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

后端 未结 14 1888
离开以前
离开以前 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:12
    function assign(obj, prop, value) {
        if (typeof prop === "string")
            prop = prop.split(".");
    
        if (prop.length > 1) {
            var e = prop.shift();
            assign(obj[e] =
                     Object.prototype.toString.call(obj[e]) === "[object Object]"
                     ? obj[e]
                     : {},
                   prop,
                   value);
        } else
            obj[prop[0]] = value;
    }
    
    var obj = {},
        propName = "foo.bar.foobar";
    
    assign(obj, propName, "Value");
    
    0 讨论(0)
  • 2020-11-22 03:15

    I know it's an old one, but I see only custom functions in answers.
    If you don't mind using a library, look at lodash _.set and _.get function.

    0 讨论(0)
提交回复
热议问题