Skip to content

Instantly share code, notes, and snippets.

@aleksihakli
Last active August 29, 2015 14:16
Show Gist options
  • Save aleksihakli/5bd69c1cd348792ecdf9 to your computer and use it in GitHub Desktop.
Save aleksihakli/5bd69c1cd348792ecdf9 to your computer and use it in GitHub Desktop.
Nested assignment of properties by dot delimited key string in CoffeeScript or JavaScript objects
# Naive recursive property assignment to object from a dot delimited string, e.g.
#
# assignNestedPropertyByKeyString {}, 'biz', 'foo.bar.bah'
# -> {foo: {bar: {bah: 'biz'}}}
assignNestedPropertyByKeyString = (obj, val, keyString) ->
_assignNestedPropertyByKeyArray = (_o, _v, _keys) ->
_k = _keys.splice 0, 1
if _.isEmpty _keys
_o[_k] = _v
else
_o[_k] = _o[_k] or {}
_assignNestedPropertyByKeyArray _o[_k], _v, _keys
if _.isEmpty keyString
throw new Error "Have to have some key to assign"
_assignNestedPropertyByKeyArray obj, val, keyString.split('.')
# Example application of the function with Lo-Dash
_.transform {'qux.gah.goh.box': 'ruh'}, assignNestedPropertyByKeyString
# -> {qux: {gah: {goh: {box: 'ruh'}}}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment