Convert string in dot notation to get the object reference [duplicate]

To obtain the value, consider:

function ref(obj, str) {
    str = str.split(".");
    for (var i = 0; i < str.length; i++)
        obj = obj[str[i]];
    return obj;
}

var obj = { a: { b: 1, c : { d : 3, e : 4}, f: 5 } }
str="a.c.d"
ref(obj, str) // 3

or in a more fancy way, using reduce:

function ref(obj, str) {
    return str.split(".").reduce(function(o, x) { return o[x] }, obj);
}

Returning an assignable reference to an object member is not possible in javascript, you’ll have to use a function like the following:

function set(obj, str, val) {
    str = str.split(".");
    while (str.length > 1)
        obj = obj[str.shift()];
    return obj[str.shift()] = val;
}

var obj = { a: { b: 1, c : { d : 3, e : 4}, f: 5 } }
str="a.c.d"
set(obj, str, 99)
console.log(obj.a.c.d) // 99

or use ref given above to obtain the reference to the containing object and then apply the [] operator to it:

parts = str.split(/\.(?=[^.]+$)/)  // Split "foo.bar.baz" into ["foo.bar", "baz"]
ref(obj, parts[0])[parts[1]] = 99

Leave a Comment