How to build a tree with lots of branches?

Hello!

Use tree.
How to build this type of structure?
For example I have data from a database in a chaotic order of appearance:
{ id, name, parentId }
(Do I need another field "Serial number"?)
To show the tree you need to bring them to mind:
[
{
 "id": 1,
 "name": "node1",
 "children": [
{
 "id": 11,
 "name": "node1.1",
 "children": [
{
 "id": 111,
 "name": "node1.1.1",
 "children": [
{
 "id": 1111,
 "name": "node1.1.1.1",
 "children": []
}
]
}
]
},
{
 "id": 12,
 "name": "node1.2",
 "children": []
}
]
}
]


How to build a loop to build the same structure?
I would appreciate links to resources to read.
July 8th 19 at 16:10
1 answer
July 8th 19 at 16:12
recursion.

updated
Although you can cycle just

function buildTree(list) {
 const map = {};

 return list
 .sort((a, b) => Number(a.pid) - Number(b.pid))
 .reduce((tree, category) => {
 if (!map[category.id]) {
 map[category.id] = {
 id: category.id
 children: []
};
}

 if (category.pid) {
map[category.pid].children.push(map[category.id]);
 } else {
tree.push(map[category.id]);
}

 return tree;
 }, []);
}
I understand what recursion is, just as on js to move the pointer to the next level?
How do I add children to the second element? - geoffrey_Ste commented on July 8th 19 at 16:15
: updated. That pointers to objects are passed by reference. - Allene_Crona78 commented on July 8th 19 at 16:18

Find more questions by tags JavaScript