Given an array of objects containing root and list elements in a tree structure, how can I efficiently organize them into a tree with an unknown depth? Each object has a parent element ID property.
I am currently working on building a menu. While I have successfully organized list elements under their respective parents, I am facing difficulties organizing all root elements without nesting loops to check if everything is properly structured.
Here is an example of the initial data: https://pastebin.com/eCSZ1HgR
[
{
"groupId": 1,
"parentGroupId": null
},
{
"groupId": 3,
"parentGroupId": 1
}, ...
]
If an object's parentGroupId is null, it indicates that it belongs to the root of the tree.
Below is the code snippet I am currently using:
for (var i = 0; i < groups.length; i++) {
var childGroup = groups[i];
if (childGroup.parentGroupId === null) {
continue;
}
for (var j = 0; j < groups.length; j++) {
var parentGroup = groups[j];
if (childGroup.parentGroupId === parentGroup.groupId) {
if (parentGroup.hasOwnProperty('children')) {
parentGroup.children.push(childGroup);
} else {
parentGroup.children = [childGroup];
}
break;
}
}
}