Created
July 11, 2017 21:54
-
-
Save unixpickle/f700c238ae4cec5f28940c327b026e68 to your computer and use it in GitHub Desktop.
Search for a key in nested JavaScript objects
This file contains 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 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