Created
June 7, 2017 19:32
-
-
Save unixpickle/2e76953a17c50f91589dde806646a3ac to your computer and use it in GitHub Desktop.
Search JavaScript objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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