Skip to content

Instantly share code, notes, and snippets.

@unixpickle
Created June 7, 2017 19:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save unixpickle/2e76953a17c50f91589dde806646a3ac to your computer and use it in GitHub Desktop.
Save unixpickle/2e76953a17c50f91589dde806646a3ac to your computer and use it in GitHub Desktop.
Search JavaScript objects
function searchValue(needle, haystack, depth) {
var recur;
recur = (findVal, obj, path, res, depth) => {
if (obj === findVal) {
res.push(path);
}
if (depth === 0) {
return;
}
if ('object' === typeof obj && obj !== null) {
var keys = Object.keys(obj);
keys.forEach((k) => recur(findVal, obj[k], path+'.'+k, res, depth-1));
}
};
var res = [];
recur(needle, haystack, 'root', res, depth);
return res;
}
// Yields ["root.hello.data"]:
searchValue('hi', {hello: {data: 'hi', name: 'Joe'}}, 3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment