Chiel ten Brinke Chiel ten Brinke - 1 year ago 69
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 = "";

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

Answer Source
function assign(obj, prop, value) {
    if (typeof prop === "string")
        prop = prop.split(".");

    if (prop.length > 1) {
        var e = prop.shift();
        assign(obj[e] =
       [e]) === "[object Object]"
                 ? obj[e]
                 : {},
    } else
        obj[prop[0]] = value;

var obj = {},
    propName = "";

assign(obj, propName, "Value");
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download