Reputation: 8556
I have the following array
var testArray = ["test1", "test2", "test3"];
and an obj
which has other object in it
var obj.test1.test2.test3 = "test";
I want to foreach the testArray
and get the following
obj[testArray[0]][testArray[1]][testArray[2]]
or obj["test1"]["test2"]["test3"]
which is equal to obj.test1.test2.test3
and will return "test"
Upvotes: 1
Views: 53
Reputation: 41842
As you stated you are aware, we can take advantage of the obj["test1"]
notation to nest ourselves deeper into the target object. In this case, on each iteration we re-assign the "top" of what we are pointing to to be the child of the last iteration.
var obj = { test1: { test2: {test3: 'test' }}};
var current = obj;
var arr = ['test1', 'test2', 'test3'];
for(var i = 0; i < arr.length; i++){
if(current === undefined){ break; }
current = current[arr[i]];
}
console.log(current);
Upvotes: 2
Reputation: 45731
function extractDeep(obj, propPathArr) {
var prop = obj;
propPathArr.forEach(function (item) {
prop = prop[item];
});
return prop;
}
call like:
alert(extractDeep({a: {b: {c: "The property!"}}}, ['a', 'b', 'c']));
NOTE:
forEach
does not work in all browsersUpvotes: 0
Reputation: 40498
How about this:
var testArray = ["test1", "test2", "test3"];
var value = [obj].concat(testArray).reduce(function(prev, curr) {
return prev[curr];
});
But remember that reduce
is not supported by IE <= 8 (Reduce reference).
Upvotes: 0