Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Snippet to recursively search a JSON structure for a leaf value - returns the path
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
@arigesher
Copy link
Author

arigesher commented Jul 26, 2015

foo = 
  baz: 
    bang: 'blah'

 console.log foo 
 console.log find_value foo, 'blah'

Yields:

{ baz: { bang: 'blah' } }
object:  { baz: { bang: 'blah' } }
needle:  blah
object:  { bang: 'blah' }
needle:  blah
baz.bang

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment