Peter Zelak Peter Zelak - 1 year ago 51
Javascript Question

Access an object with the keys in an array

I have an object and I want to access this:


problem is I have an array where I store those keys:

arr = ['example', 'example-2', 'example-3'];

but this array can be of variable length so maybe it's just 3 keys maybe there are 6.
How can I achieve this without hardcoding each case, for example:

if(arr.length == 1){
}else if (arr.length == 2){


Answer Source

You could use the path and reduce the object.

function getValue(o, path) {
    return path.reduce(function (o, k) {
        return (o || {})[k];
    }, o);

var obj = { example: { 'example-2': { 'example-3': 42 } } },
    arr = ['example', 'example-2', 'example-3'];

console.log(getValue(obj, arr));

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