1

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

5
  • Iterate through the array, looking up the value in the "current" map, starting with the top and carrying the next on ;) Commented Dec 31, 2014 at 7:23
  • 1
    Not sure this question really belongs here, there's not much to this: jsfiddle.net/5ftkcbpe Commented Dec 31, 2014 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 Commented Dec 31, 2014 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. Commented Dec 31, 2014 at 7:33
  • 1
    Actually reduce would make more sense: jsfiddle.net/5ftkcbpe/1 Commented Dec 31, 2014 at 7:43

1 Answer 1

1

var keys = ['folder','name'];
var data = { folder: { name: 'Special Folder' } };
for(var i=0;i<keys.length;i++){
    data = data[keys[i]];
}
alert(data)

Sign up to request clarification or add additional context in comments.

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.