Skip to content

Commit 6cfc561

Browse files
committed
feat: add tree to list
1 parent a4f0378 commit 6cfc561

File tree

1 file changed

+113
-0
lines changed

1 file changed

+113
-0
lines changed

js/tree_to_list.js

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
/*
2+
* @Author: Chacha
3+
* @Date: 2022-05-09 23:25:02
4+
* @Last Modified by: Chacha
5+
* @Last Modified time: 2022-05-09 23:25:25
6+
*/
7+
8+
/**
9+
*
10+
[
11+
{
12+
"id": 1,
13+
"name": "部门1",
14+
"pid": 0,
15+
"children": [
16+
{
17+
"id": 2,
18+
"name": "部门2",
19+
"pid": 1,
20+
"children": []
21+
},
22+
{
23+
"id": 3,
24+
"name": "部门3",
25+
"pid": 1,
26+
"children": [
27+
{
28+
"id": 4,
29+
"name": "部门4",
30+
"pid": 3,
31+
"children": [
32+
{
33+
"id": 5,
34+
"name": "部门5",
35+
"pid": 4,
36+
"children": []
37+
}
38+
]
39+
}
40+
]
41+
}
42+
]
43+
}
44+
]
45+
=>
46+
[
47+
{id: 1, name: '部门1', pid: 0},
48+
{id: 2, name: '部门2', pid: 1},
49+
{id: 3, name: '部门3', pid: 1},
50+
{id: 4, name: '部门4', pid: 3},
51+
{id: 5, name: '部门5', pid: 4},
52+
]
53+
*
54+
*/
55+
56+
const tree2list = (tree) => {
57+
let list = [];
58+
let queue = [...tree];
59+
60+
while (queue.length) {
61+
// 从前面开始取出节点
62+
const node = queue.shift();
63+
const children = node.children;
64+
65+
if (children.length) {
66+
queue.push(...children);
67+
}
68+
// 删除多余的children树形
69+
delete node.children;
70+
71+
list.push(node);
72+
}
73+
74+
return list;
75+
};
76+
77+
const data = [
78+
{
79+
id: 1,
80+
name: "部门1",
81+
pid: 0,
82+
children: [
83+
{
84+
id: 2,
85+
name: "部门2",
86+
pid: 1,
87+
children: [],
88+
},
89+
{
90+
id: 3,
91+
name: "部门3",
92+
pid: 1,
93+
children: [
94+
{
95+
id: 4,
96+
name: "部门4",
97+
pid: 3,
98+
children: [
99+
{
100+
id: 5,
101+
name: "部门5",
102+
pid: 4,
103+
children: [],
104+
},
105+
],
106+
},
107+
],
108+
},
109+
],
110+
},
111+
];
112+
113+
console.log(tree2list(data));

0 commit comments

Comments
 (0)