Here is an array of objects:
[
{
"id": 1942,
"label": "1",
"url": "",
"homepage": false,
"visible": true,
"order": 1
},
{
"id": 1943,
"label": "a",
"url": "",
"parentId": 1942,
"homepage": false,
"visible": true,
"order": 1
},
...
The task at hand is to generate a menu with links based on the parent-child relationships in the array.
The new array structure needed for this purpose should be formatted as follows:
1
1 / a
1 / aa
1 / aaa
1 / a / a1
1 / a / a2
2
2 / b
2 / bb
2 / b / b1
2 / b / b2
Multiple attempts have been made, including recursion and looping techniques:
convert(array) {
const x = array
.filter((m, i) => m.id === array[i].parentId)
.map((menuItem) => ({
parent: menuItem,
children: convert(array),
}));
console.log(x)
}
Yet, none has succeeded in achieving infinite levels of depth. Here is one such attempt:
convert() {
let parents = array.filter((p) => !p.parentId);
const children = array.filter((c) => c.parentId);
let combined = [];
// Loops used here...
console.log(combined);
}
UPDATE: While I managed to achieve 3 levels of depth, recursive solution for unlimited depth remains unresolved.
convert() {
let parents = this.config.menuItems.filter((p) => !p.parentId);
const children = this.config.menuItems.filter((c) => c.parentId);
let combined = [];
// More loops with 3-level depth...
console.log(combined);
}