Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I think a code sample is going to work a lot better than my vocabulary:

var keys = ['folder','name'];

var data = { folder: { name: 'Special Folder' } };

Given the two vars above, I'm looking for a way to dynamically use the array as a way to look up the object keys (sort of like a "path"). So I need to programmatically produce the following:

data['folder']['name'] // that would give me 'Special Folder'

Hopefully this makes sense, I just can't quite put all the pieces together.

TIA

share|improve this question
    
Iterate through the array, looking up the value in the "current" map, starting with the top and carrying the next on ;) –  Rob Y Dec 31 '14 at 7:23
1  
Not sure this question really belongs here, there's not much to this: jsfiddle.net/5ftkcbpe –  Hey Dec 31 '14 at 7:27
    
@Hey I'm not sure why this didn't click. I've done this very thing more than couple times in the past, but tonight I just couldn't put it into code for some reason. Thanks –  rpaskett Dec 31 '14 at 7:32
    
@rpaskett no problem... this one won't throw anything if it can't resolve, it'll just return undefined. Change (target || {}) to target if you want it to throw an error for a set of keys it can't resolve. –  Hey Dec 31 '14 at 7:33
1  
Actually reduce would make more sense: jsfiddle.net/5ftkcbpe/1 –  Hey Dec 31 '14 at 7:43

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.