Sometimes we need to construct a tree array structure from a flat array structure (flat array) based on id and pid. This situation often occurs in nested directory structures, as shown below:
Or the departmental structure of the enterprise will also have a similar structure above.
Similar to the above scenario, if we have the following data:
let entries = [{
"id": "12",
"parentId": "0",
"text": "Man",
"level": "1",
"children": null
},
{
"id": "7",
"parentId": "12",
"text": "Other",
"level": "2",
"children": null
},
{
"id": "8",
"parentId": "7",
"text": "Bird",
"level": "3",
"children": null
},
{
"id": "9",
"parentId": "0",
"text": "Woman",
"level": "1",
"children": null
},
{
"id": "11",
"parentId": "9",
"text": "Girl",
"level": "2",
"children": null
}
];
We expect to construct the following structure through an algorithm:
[
{
"id": "12",
"parentId": "0",
"text": "Man",
"level": "1",
"children": [
{
"id": "7",
"parentId": "12",
"text": "Other",
"level": "2",
"children": [
{
"id": "8",
"parentId": "7",
"text": "Bird",
"level": "3",
"children": []
}
]
}
]
},
{
"id": "9",
"parentId": "0",
"text": "Woman",
"level": "1",
"children": [
{
"id": "11",
"parentId": "9",
"text": "Girl",
"level": "2",
"children": []
}
]
}
]
Maybe we can think of using recursion when traversing the array. It's true that the problem can be solved, but it's not efficient this way.
Recently, I saw a method on Stack Overflow, I felt good, posted it and shared it:
function list_to_tree(list) {
var map = {}, node, roots = [], i;
for (i = 0; i < list.length; i += 1) {
map[list[i].id] = i; // initialize the map
list[i].children = []; // initialize the children
}
for (i = 0; i < list.length; i += 1) {
node = list[i];
if (node.parentId !== "0") {
// if you have dangling branches check that map[node.parentId] exists
list[map[node.parentId]].children.push(node);
} else {
roots.push(node);
}
}
return roots;
}
The complexity of the algorithm is Θ(n log(n)).
If recursion is used, the complexity is Θ(n^2). If the data set is relatively large, the execution time will be very long.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。