Bluefire Bluefire - 4 months ago 13
Javascript Question

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

Given an object

, 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";



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