1

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

4
  • What should happen if some value doesn't exist in the object? Commented Apr 12, 2014 at 14:00
  • it should just be ignored Commented Apr 12, 2014 at 14:00
  • Nope. That is not clear. Can you please show what exactly is your expected output, in both the cases? Commented Apr 12, 2014 at 14:01
  • added an explanation to the question Commented Apr 12, 2014 at 14:05

2 Answers 2

3

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

tester[myarray[0]]
Sign up to request clarification or add additional context in comments.

2 Comments

thank you this works. i edited my question slightly just now (sorry). Just an additional requirement regarding possible nesting
I recommend going over to jsfiddle and trying this stuff out. Constructions such as a[b[c[d]]] and a[b][c][d] are totally fine.
1

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

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.