The parent id represents another category id which is its parent. With the dataset below I try to accomplish programmatically a structure like this:
| Cat Top Level 1
| Cat Top Level 2
| Cat Top Level 3
| --- Cat Top 3 Child 1
| --- Cat Top 3 Child 2
| ------ Cat Top 3 Child 2 Child 1
| --------- Cat Top 3 Child 2 Child 1 Child 1
| --- Cat Top 3 Child 3
The objects need to be merged into one and other. If a 'child' category is pushed into its direct 'parent' category it must come in a newly to create property called 'children' (array).
Dataset:
const categories = [
{
id: 16,
name: "Cat Top Level 1",
parent: 0,
},
{
id: 17,
name: "Cat Top Level 2",
parent: 0,
},
{
id: 18,
name: "Cat Top Level 3",
parent: 0,
},
{
id: 19,
name: "Cat Top 3 Child 1",
parent: 18,
},
{
id: 20,
name: "Cat Top 3 Child 2",
parent: 18,
},
{
id: 22,
name: "Cat Top 3 Child 2 Child 1",
parent: 20,
},
{
id: 23,
name: "Cat Top 3 Child 2 Child 1 Child 1",
parent: 22,
},
{
id: 21,
name: "Cat Top 3 Child 3",
parent: 18,
},
{
id: 15,
name: "Uncategorized",
parent: 0,
},
];
The code that I came up with so far goes like this.
function mergeCategories(categories) {
categories.map((category) => {
category.children = [];
if (category.parent === 0) {
return;
}
categories.map((subCategory) => {
if (subCategory.id !== category.parent) {
return;
}
});
});
}
Loop in a loop will return many duplicates. A .filter() seems to be needed as well, I guess. Due to performance .forEach() is excluded.
It is by far not complete, and does not work, of course. My mind is going crazy when I'm thinking of how to approach this. I thought It would be simple. But it's quite hard to be honest.