Skip to content

Instantly share code, notes, and snippets.

@arigesher
Last active August 29, 2015 14:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save arigesher/2b4fac4efac65e9f5e4b to your computer and use it in GitHub Desktop.
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
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

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