Skip to content

Instantly share code, notes, and snippets.

@unixpickle
Created July 11, 2017 21:54
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 unixpickle/f700c238ae4cec5f28940c327b026e68 to your computer and use it in GitHub Desktop.
Save unixpickle/f700c238ae4cec5f28940c327b026e68 to your computer and use it in GitHub Desktop.
Search for a key in nested JavaScript objects
function searchKey(needle, haystack, depth) {
var recur;
recur = (obj, path, res, depth, key) => {
if (key === needle) {
res.push(path);
}
if (depth === 0) {
return;
}
if ('object' === typeof obj && obj !== null) {
var keys = Object.keys(obj);
keys.forEach((k) => recur(obj[k], path+'.'+k, res, depth-1, k));
}
};
var res = [];
recur(haystack, '', res, depth, '');
return res;
}
// Yields [".dontLook.myKey.monkey"]
searchKey('monkey', {dontLook: {myKey: {monkey: 3}, otherKey: false}}, 3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment