Skip to content

Instantly share code, notes, and snippets.

@fukayatsu
Created April 1, 2012 10:49
Show Gist options
  • Save fukayatsu/2274489 to your computer and use it in GitHub Desktop.
Save fukayatsu/2274489 to your computer and use it in GitHub Desktop.
オブジェクトを階層化(?)する
describe 'tree', ->
describe 'キーにコロンを含まないとき', ->
it 'そのままのオブジェクトが返ってくること', ->
expect({'a': 1}).toEqual {a: 1}
expect({'a': 1,'b': 2}).toEqual {a:1, b:2}
describe 'キーがコロンでセパレートされているとき', ->
it '階層化されて返ってくること', ->
expect( tree {'a:b':1, 'c:d':2} ).toEqual {a:{b:1},c:{d:2}}
expect( tree {'a:b:c':1, 'a:b:d':2} ).toEqual {a:{b:{c:1, d:2}}}
tree = (obj) ->
return if typeof obj isnt 'object'
for key of obj
k = key.split(':')
continue if k.length < 2
obj[k[0]] ?= {}
obj[k[0]][k[1..-1].join(':')] = obj[key]
delete obj[key]
tree(obj[k[0]])
obj
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment