Reputation: 4342
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.
Upvotes: 2
Views: 981
Reputation: 51211
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.
Upvotes: 1
Reputation: 298166
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);
Upvotes: 4