Skip to content

Commit a4f0378

Browse files
committedMay 9, 2022
feat: add list to tree
1 parent 221b9cd commit a4f0378

File tree

1 file changed

+95
-0
lines changed

1 file changed

+95
-0
lines changed
 

‎js/list_to_tree.js

+95
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
/*
2+
* @Author: Chacha
3+
* @Date: 2022-05-09 23:13:53
4+
* @Last Modified by: Chacha
5+
* @Last Modified time: 2022-05-09 23:15:09
6+
*/
7+
8+
/**
9+
*
10+
let arr = [
11+
{id: 1, name: '部门1', pid: 0},
12+
{id: 2, name: '部门2', pid: 1},
13+
{id: 3, name: '部门3', pid: 1},
14+
{id: 4, name: '部门4', pid: 3},
15+
{id: 5, name: '部门5', pid: 4},
16+
]
17+
=>
18+
[
19+
{
20+
"id": 1,
21+
"name": "部门1",
22+
"pid": 0,
23+
"children": [
24+
{
25+
"id": 2,
26+
"name": "部门2",
27+
"pid": 1,
28+
"children": []
29+
},
30+
{
31+
"id": 3,
32+
"name": "部门3",
33+
"pid": 1,
34+
"children": [
35+
// 结果 ,,,
36+
]
37+
}
38+
]
39+
}
40+
]
41+
*
42+
*
43+
*/
44+
// 非递归版本
45+
const arrayToTree = (array) => {
46+
const hashMap = {};
47+
let result = [];
48+
49+
array.forEach((it) => {
50+
const { id, pid } = it;
51+
52+
// 不存在时,先声明children树形
53+
// 这一步也有可能在下面出现
54+
if (!hashMap[id]) {
55+
hashMap[id] = {
56+
children: [],
57+
};
58+
}
59+
60+
hashMap[id] = {
61+
...it,
62+
children: hashMap[id].children,
63+
};
64+
// 处理当前的item
65+
const treeIt = hashMap[id];
66+
67+
// 根节点,直接push
68+
if (pid === 0) {
69+
result.push(treeIt);
70+
} else {
71+
// 也有可能当前节点的父父节点还没有加入hashMap,所以需要单独处理一下
72+
if (!hashMap[pid]) {
73+
hashMap[pid] = {
74+
children: [],
75+
};
76+
}
77+
// 非根节点的话,找到父节点,把自己塞到父节点的children中即可
78+
hashMap[pid].children.push(treeIt);
79+
}
80+
});
81+
82+
return result;
83+
};
84+
85+
const data = [
86+
// 注意这里,专门把pid为1的元素放一个在前面
87+
{ id: 2, name: "部门2", pid: 1 },
88+
{ id: 1, name: "部门1", pid: 0 },
89+
{ id: 3, name: "部门3", pid: 1 },
90+
{ id: 4, name: "部门4", pid: 3 },
91+
{ id: 5, name: "部门5", pid: 4 },
92+
{ id: 7, name: "部门7", pid: 6 },
93+
];
94+
95+
console.log(JSON.stringify(arrayToTree(data), null, 2));

0 commit comments

Comments
 (0)
Failed to load comments.