1

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"

0

3 Answers 3

2

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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).

Comments

0
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:

  • You really should add some error checking.
  • forEach does not work in all browsers

jsFiddle can be found here

Comments

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.