Skip to content

Instantly share code, notes, and snippets.

@Akiyamka
Last active June 17, 2018 13:34
Show Gist options
  • Select an option

  • Save Akiyamka/c1648c812c0be62fb767f1b1771f12c2 to your computer and use it in GitHub Desktop.

Select an option

Save Akiyamka/c1648c812c0be62fb767f1b1771f12c2 to your computer and use it in GitHub Desktop.
Create tree from flat array
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