Input
let categories =[
{id:1, name:'Electronics', parentId:''},
{id:2, name:'Devices', parentId:1},
{id:3, name:'Mobile Phones', parentId:2},
{id:4, name:'TV', parentId:2},
{id:5, name:'Accessories', parentId:1},
{id:6, name:'Beauty', parentId:''},
]
Expected Output
let categories =[
{id:1, name:'Electronics', parentId:'', subCategories:[
{id:2, name:'Devices', parentId:1, subCategories:[
{id:3, name:'Mobile Phones', parentId:2},
{id:4, name:'TV', parentId:2}}
]
},
{id:5, name:'Accessories', parentId:1}
]
},
{id:6, name:'Beauty',parentId:''}
]
Explanation
So above in Input array
id:1 and id:6 has no parentId. That means they are the root categories in Expected Output.
id:2 and id:5 has parentId:1. That means they are
subcategories of id:1 and goes into the subCategories array of id:1.id:3 and id:4 has parentId:2. That means they are subcategories of id:2 and goes into the subCategories array of id:2.
and there could be more nested subCategories.
for example
A new object id:7 can have a parentId:4.So it is a subCategory of id:4 and goes into the subCategories array of id:4
2
Answers
You could build a tree with all related pairs children/parent, parent/children and return the nodes with no parent
''
as tree.You can use
map
to create helpercatObj
where key is the id and value is the item of categories. Next useforEach
loop to conditionally push sub-categories or root-categories to the adequate array based on the existence ofparentCat
.