Marty Wallace
Marty Wallace

Reputation: 35796

javascript - select json object item based on array value

if i have an array of values:

['test1', 'test2', 'test3']

and a json object:

var tester = {'test1' : 'test 1 value', 'test2' : 'test 2 value' }

how can i use the array values as a selector to the json object.

I tried: tester.myarray[0]

but that obviously didnt work.

EDIT:

Additionally, i might need to work with nested values like:

 var myArray = ['test1', 'test2']

 var tester = {'test1' : { 'test2' : 'test 1/2 value'}}

so in this example i have an array, myArray which essentially contains the path of where to find the value in the json object. i.e tester.test1.test2.

I would expect to based on the array be able to find the value in the json object

Importantly, the size of the path is not known up front so i assume i will need to loop over the array values to build the path

Upvotes: 1

Views: 1416

Answers (2)

thefourtheye
thefourtheye

Reputation: 239653

You can use Array.prototype.map to get the corresponding elements from the object

var array1 = ['test1', 'test2', 'test3'],
    tester = {'test1' : 'test 1 value', 'test2' : 'test 2 value' };

console.log(array1.map(function(currentKey) {
    return tester[currentKey];
}));
# [ 'test 1 value', 'test 2 value', undefined ]

Edit: As per your latest edit, if you want to get the data from the nested structure, you can do it with Array.prototype.reduce like this

console.log(myArray.reduce(function(result, current) {
    return result[current];
}, tester));
# test 1/2 value

Upvotes: 1

awm
awm

Reputation: 6580

I believe this is the expression you're looking for.

tester[myarray[0]]

Upvotes: 3

Related Questions