Mdb
Mdb

Reputation: 8556

javascript construct an object from an array of strings

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

Answers (3)

Matt
Matt

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

PatrikAkerstrand
PatrikAkerstrand

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:

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

jsFiddle can be found here

Upvotes: 0

Amberlamps
Amberlamps

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

Related Questions