Last active
August 29, 2015 14:25
-
-
Save arigesher/2b4fac4efac65e9f5e4b to your computer and use it in GitHub Desktop.
Snippet to recursively search a JSON structure for a leaf value - returns the path
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
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: