Skip to content

Instantly share code, notes, and snippets.

Last active August 29, 2015 14:25
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
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
if haystack?
unless typeof haystack == 'object' and cache.has haystack
cache.set haystack, true
for key, value of haystack
if value == needle
return key
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
Copy link

foo = 
    bang: 'blah'

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


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

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