Skip to content

Instantly share code, notes, and snippets.

@jond3k
Created November 9, 2011 17:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jond3k/1352258 to your computer and use it in GitHub Desktop.
Save jond3k/1352258 to your computer and use it in GitHub Desktop.
Two ways to crawl objects with an array of 'directions'. re: https://gist.github.com/1351684
var obj = {a:{b:{c:':D'}}};
var path = ['a','b','c'];
var path2 = ['a','b','c'];
console.log(crawl(obj, path));
console.log(crawl2(obj, path2));
function crawl2(obj, keys) {
while(keys.length) {
obj = obj[keys.shift()];
}
return obj;
}
function crawl(obj, keys) {
var key = keys.shift();
return keys.length == 0 ? obj[key] : crawl(obj[key], keys);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment