Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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;
- }, {})
Add Comment
Please, Sign In to add comment