Bluefire Bluefire - 1 year ago 64
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";


Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download