Bluefire Bluefire - 3 months ago 8
Javascript Question

How to modify an object property given its location within the object

Given an object

obj
, I can modify its properties by using something like
obj.a.b.c = "new value"
. However, I want to be able to do this programmatically, with the property's location in the form of an array. How can I make a function that looks like this:

modifyProperty(obj, ["a", "b", "c"], "new value");


and is equivalent to

obj.a.b.c = "new value";


?

Answer

You could use Array#reduce for it, with a default object if no object is available.

function modifyProperty(object, path, value) {
    var last = path.pop();
    path.reduce(function (r, a) {
        if (!(a in r)) {
            r[a] = {};
        }
        return r[a];
    }, object)[last] = value;
}

var object = {};
modifyProperty(object, ["a", "b", "c"], "new value");
console.log(object);

Comments