rpaskett
rpaskett

Reputation: 456

Traverse nested maps / objects from keys in an array

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

Upvotes: 1

Views: 1731

Answers (1)

Lewis
Lewis

Reputation: 14866

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

Upvotes: 1

Related Questions