Last active
June 17, 2018 13:34
-
-
Save Akiyamka/c1648c812c0be62fb767f1b1771f12c2 to your computer and use it in GitHub Desktop.
Create tree from flat array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const childs = [ | |
| { | |
| id: 'foo|bar|baz|bug', | |
| name: 'foo, bar, baz, bugger', | |
| }, | |
| { | |
| id: 'foo', | |
| name: 'foorer' | |
| }, | |
| { | |
| id: 'foo|bar', | |
| name: 'foo, barer', | |
| }, | |
| { | |
| id: 'foo|bar|kek', | |
| name: 'foo, bar, keker', | |
| }, | |
| { | |
| id: 'bad|bar|kek', | |
| name: 'bad, bar, keker', | |
| } | |
| ] | |
| function goDeeper(tree, levels, child) { | |
| let curentLevel = levels.shift(); | |
| if (levels.length > 0) { | |
| tree[curentLevel] = tree[curentLevel] || {}; | |
| return goDeeper(tree[curentLevel], levels, child); | |
| } else { | |
| tree[curentLevel] = {...child, ...tree[curentLevel]}; | |
| return tree; | |
| } | |
| } | |
| function addLevel(child, tree) { | |
| let levels = child.id.split('|'); | |
| goDeeper(tree, levels, child); | |
| return tree; | |
| } | |
| let tree = childs.reduce((acc, c) => { | |
| addLevel(c, acc); | |
| return acc; | |
| }, {}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment