Snippet to recursively search a JSON structure for a leaf value - returns the path
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
find_value = (haystack, needle, cache=new WeakMap()) -> | |
# console.log "haystack: ", haystack | |
# console.log "needle: ", needle | |
try | |
if haystack? | |
unless typeof haystack == 'object' and cache.has haystack | |
cache.set haystack, true | |
for key, value of haystack | |
if value == needle | |
return key | |
else | |
if typeof value == 'object' | |
found = find_value value, needle, cache | |
if found? | |
return "#{key}.#{found}" | |
return null | |
catch err | |
console.error typeof haystack, haystack | |
console.error typeof needle, needle | |
console.error err | |
return null |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yields: