Access to nested objects through an array of property names

Let's say I have an object like this (simplified):

var options = {
    boxes: {
        size: {
            x: 15,
            y: 18
        },
    shadow: {
        [...]
    }
};

And I have an array of names:

var names = ['boxes', 'size', 'x'];

What is an easy way to get / set the value inside the object according to the array, in this example it will be:

options.boxes.size.x = somevalue;

Any ideas?

+4
source share
2 answers

There is no simple, built-in method for this. You will have to write your own method:

function getPath(obj, props) {
    for(var i = 0; i < props.length; i++) {
        if (props[i] in obj) {
            obj = obj[props[i]];
        } else {
            return; // not found
        }
    }

    return obj;
}

function setPath(obj, value, props) {
    for(var i = 0; i < props.length - 1; i++) {
        if (props[i] in obj) {
            obj = obj[props[i]];
        } else {
            return; // not found
        }
    }

    obj[props[i]] = value;
}

alert(getPath(options, names)); // 15
setPath(options, 25, names);  
alert(getPath(options, names)); // 25
+4
source

Just use a loop that iterates namesand grabs the next nested object for the current name. Either false or the end of the array should stop the loop.

var obj = options;
var i = 0;

while (obj && i < names.length)
    obj = obj[names[i++]];

Or just use .reduce()

names.reduce(function(obj, name) {
    return obj && obj[name];
}, options);

, , , .

function toPropertyIn(obj, name) {
    return obj && obj[name];
}

names.reduce(toPropertyIn, options);

/:

function nestedProp(obj, names, value) {
    if (arguments.length > 1)
        var setProp = names.pop();

    var res = names.reduce(function(obj, name) {
        return obj && obj[name];
    }, options);

    if (res && setProp !== undefined)
        res[setProp] = value;
    else
        return res;
}


nestedProp(options, names, "foo"); // to set

var val = nestedProp(options, names); // to get
+4

All Articles