JSFiddle - React, Tailwind, and code Playground
JavaScript
let categories = [{
id: 'animals',
parent: null
},
{
id: 'mammals',
parent: 'animals'
},
{
id: 'cats',
parent: 'mammals'
},
{
id: 'dogs',
parent: 'mammals'
},
{
id: 'chihuahua',
parent: 'dogs'
},
{
id: 'rex',
parent: 'dogs'
},
{
id: 'labrador',
parent: 'dogs'
},
{
id: 'persian',
parent: 'cats'
},
{
id: 'siamese',
parent: 'cats'
}
];
function makeTree(categories, parent) {
let node = {};
const filteredArr = categories.filter(c => c.parent === parent);
console.log('level arr', filteredArr)
for (let obj of filteredArr) {
const nodeToAppend = makeTree(categories, obj.id);
console.log('node to append:', nodeToAppend)
node[obj.id] = nodeToAppend;
}
return node;
}
console.log(makeTree(categories, null));