Recursion 2
by Matthew Day
JavaScript
let categories = [
{ id: 'animals', parent: null },
{ id: 'mammals', parent: 'animals' },
{ id: 'cats', parent: 'mammals' },
{ id: 'dogs', parent: 'mammals' },
{ id: 'chihuahua', parent: 'dogs' },
{ id: 'labrador', parent: 'dogs' },
{ id: 'persian', parent: 'cats' },
{ id: 'siamese', parent: 'cats' },
]
let makeTree = (categories, parent) => {
let node = {};
categories
.filter(c => c.parent === parent)
.forEach(c => node[c.id] = makeTree(categories, c.id))
return node;
}
console.log(
JSON.stringify(
makeTree(categories, null), null, 2
)
);
// NOTES
// It may be worth looking into refactoring this code with Promise.
// SOURCE
// https://www.youtube.com/watch?v=k7-N8R0-KY4