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