You can store the previous property's value (initially obj) and continue to loop until end of array like so:
var arr = ['one', 'two', 'three'];
var obj = {
one: {
two: {
three: 11234
}
}
}
var currentProp = obj;
for(var i = 0; i < arr.length; i++) {
currentProp = currentProp[arr[i]];
}
console.log(currentProp);
The above code will start at the object obj, then loop until the array's length, and reassign currentProp to the next property in the array as it goes. In this case, this is what it does:
- First iteration, access
obj[arr[0]], which is one, and assign it to currentProp
- Second iteration, access
obj[arr[0]][arr[1]] or one[arr[1]], which is two, and assign it to currentProp
- Third iteration, access
obj[arr[0]][arr[1]][arr[2]] or two[arr[2]], which is three, and assign it to currentProp. Loop then terminates as it has reached end of the list.
In the end, the value of the last property will be in currentProp, and will correctly output 11234.