使用js递归生成树形结构
# 1、代码如下
const setTreeData = (data, pid, pidName = 'parentId', idName = 'id', childrenName = 'children', key) => {
let arr = [];
for (let i = 0; i < data.length; i++) {
if (data[i][pidName] == pid) {
data[i].key = data[i][idName];
data[i][childrenName] = setTreeData(data, data[i][idName], pidName, idName, childrenName);
arr.push(data[i]);
}
}
return arr;
}
let data = [
{
"id": 1,
"name": "1楼",
"parentId": 0
},
{
"id": 2,
"name": "2楼",
"parentId": 0
},
{
"id": 4,
"name": "1楼儿子2",
"parentId": 1
},
{
"id": 6,
"name": "dddddd",
"parentId": 4
},
{
"id": 12,
"name": "566666",
"parentId": 2
},
{
"id": 13,
"name": "3楼",
"parentId": 0
},
{
"id": 14,
"name": "sdsdcasw3",
"parentId": 13
},
{
"id": 15,
"name": "1312",
"parentId": 6
}
];
// 使用
let newData = setTreeData(data, 0);
console.log(newData);
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
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
# 2、运行结果
上次更新: 2024/01/30, 00:35:17
- 01
- linux 在没有 sudo 权限下安装 Ollama 框架12-23
- 02
- Express 与 vue3 使用 sse 实现消息推送(长连接)12-20