Chiel ten Brinke Chiel ten Brinke - 13 days ago 9
Javascript Question

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



Suppose we are only given

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


How can we set the property
obj.foo.bar.foobar
to a certain value (say "hello world")?
So I want to achieve this, while we only have the property name in a string:

obj.foo.bar.foobar = "hello world";

Answer
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");