Skip to content

Instantly share code, notes, and snippets.

@jossmac
Last active August 20, 2018 06:20
Show Gist options
  • Save jossmac/6e1a97df43f31aa433951e0f749d0548 to your computer and use it in GitHub Desktop.
Save jossmac/6e1a97df43f31aa433951e0f749d0548 to your computer and use it in GitHub Desktop.
Experiment: Recursion
const CATEGORIES = [
{ id: 'animals', parent: null },
{ id: 'mammals', parent: 'animals' },
{ id: 'cats', parent: 'mammals' },
{ id: 'dogs', parent: 'mammals' },
{ id: 'labrador', parent: 'dogs' },
{ id: 'cocker spaniel', parent: 'dogs' },
{ id: 'rag doll', parent: 'cats' },
{ id: 'burmese', parent: 'cats' },
];
let i = 0;
const makeTree = (items, parent) => {
let node = {};
items
.filter(c => c.parent === parent)
.forEach(c => {
console.log(i++, c.id, parent);
node[c.id] = makeTree(items, c.id);
});
return node;
};
console.log(JSON.stringify(
makeTree(CATEGORIES, null), null, 2
));
{
"animals": {
"mammals": {
"cats": {
"rag doll": {},
"burmese": {}
},
"dogs": {
"labrador": {},
"cocker spaniel": {}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment