# 平铺数组转树状结构
点击查看代码
type CfgType = {
rootId?: string;
id?: string;
parentId?: string;
children?: string;
leaf?: string;
}
type BackCategoryItem = {
cate: string;
}
interface CategoryItem {
categoryId: number;
categoryName: string;
level: number;
parentId: number;
backCategoryList: BackCategoryItem[]
}
interface ICategoryItem extends CategoryItem {
children?: ICategoryItem[]
}
// 平铺结构转树状结构
function list2Tree(list: CategoryItem[], cfg: CfgType): ICategoryItem[] {
let nodes = {}, parentNodes = {}
let prop = Object.assign({
rootId: 'root',
id: 'id',
parentId: 'parentId',
children: 'children',
leaf: 'leaf',
}, cfg)
list.forEach((node) => {
let id = node[prop.id];
let parentId = node[prop.parentId] || prop.rootId;
nodes[id] = node
if (parentId) {
parentNodes[parentId] = parentNodes[parentId] || []
parentNodes[parentId].push(node)
}
})
Object.keys(nodes).forEach(id => {
let node = nodes[id]
if (parentNodes[id]) {
node[prop.children] = parentNodes[id]
}
// else {
// node[prop.leaf] = true
// }
})
return parentNodes[prop.rootId]
}
// Test
const list: CategoryItem[] = [
{
categoryId: 1,
categoryName: '1',
level: 1,
parentId: 0,
backCategoryList: [
{
cate: '1-1',
},
{
cate: '1-2',
},
{
cate: '1-3',
},
],
},
{
categoryId: 2,
categoryName: '2',
level: 2,
parentId: 1,
backCategoryList: [
{
cate: '2-1',
},
{
cate: '2-2',
},
{
cate: '2-3',
},
],
},
{
categoryId: 3,
categoryName: '3',
level: 3,
parentId: 2,
backCategoryList: [
{
cate: '3-1',
},
{
cate: '3-2',
},
{
cate: '3-3',
},
],
}
]
const result = list2Tree(list, { id: 'categoryId' })
console.log(result);
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114