2

Let's say I have an array with unknown number of values. For example: ['one', 'two', 'three'].

How can I construct a square bracket notation for an object from it? Basically, I need to create this: var result = myObject['one']['two']['three'].

They key here is to understand that there can be any number of values in the array and I just need to go n-levels deep into the object using these values.

2 Answers 2

4

You can use a loop:

var o = myObject;

for (var i = 0; i < yourArray.length; i++) {
    o = o[yourArray[i]];
}

Or with Array.reduce, which looks nicer but won't work in older browsers:

var o = {
    'one': {
        'two': {
            'three': 'four'
        }
    }
};

['one', 'two', 'three'].reduce(function(object, key) {
    return object[key];
}, o);
Sign up to request clarification or add additional context in comments.

2 Comments

yeah, noob me misunderstood the question and embarrassed myself by making fun on others ... x_x
Thanks! Decided to use reduce() because I need this on node.js only :)
1

Short and precise with help of Array.reduce():

var o = { 'one': { 'two': { 'three': 'five' } } };
["one","two","three"].reduce(function(prev,cur){return prev[cur]},o);

reduce works from IE9 on.

2 Comments

That's the reverse of what the OP wants…
@Bergi just recognized that... ;) fixed it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.