Skip to content

Instantly share code, notes, and snippets.

@isaksky
Created October 8, 2012 21:01
Show Gist options
  • Save isaksky/3854955 to your computer and use it in GitHub Desktop.
Save isaksky/3854955 to your computer and use it in GitHub Desktop.
set/access multiple keys
update_in = (obj, keys, value) ->
node = obj
while true
key = keys.shift()
if keys.length > 0
node[key] = {} unless node[key]?
node = node[key]
else
node[key] = value
break
obj
# Look up multiple nested keys
# For example, get_in({a:{b:99}}, ["a", "b"]) => 99
get_in = (obj, keys, deflt = null) ->
x = null
node = obj
while true
key = keys.shift()
if keys.length > 0
node = node[key]
return deflt unless node?
else
x = node[key]
break
if x? then x else deflt
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment