listToTree

说明

简将列表数据转化为树结构

源码

用法

listToTree.test.ts
1
import listToTree from "../../utility/others/listToTree";
2
3
describe('listToTree tests()...', () => {
4
test('listToTree should transform a list to a tree', () => {
5
const received = [
6
{
7
id: 2,
8
value: 2,
9
parent: 1,
10
},
11
{
12
id: 3,
13
value: 3,
14
parent: 0,
15
},
16
{
17
id: 4,
18
value: 4,
19
parent: 3,
20
},
21
{
22
id: 5,
23
value: 5,
24
parent: 3,
25
},
26
{
27
id: 1,
28
value: 1,
29
parent: 0,
30
},
31
{
32
id: 6,
33
value: 6,
34
parent: 4,
35
},
36
{
37
id: 7,
38
value: 7,
39
parent: 4,
40
},
41
{
42
id: 8,
43
value: 8,
44
parent: 7,
45
},
46
];
47
const expected = [
48
{
49
"id": 3,
50
"value": 3,
51
"parent": 0,
52
"children": [
53
{
54
"id": 4,
55
"value": 4,
56
"parent": 3,
57
"children": [
58
{
59
"id": 6,
60
"value": 6,
61
"parent": 4
62
},
63
{
64
"id": 7,
65
"value": 7,
66
"parent": 4,
67
"children": [
68
{
69
"id": 8,
70
"value": 8,
71
"parent": 7
72
}
73
]
74
}
75
]
76
},
77
{
78
"id": 5,
79
"value": 5,
80
"parent": 3
81
}
82
]
83
},
84
{
85
"id": 1,
86
"value": 1,
87
"parent": 0,
88
"children": [
89
{
90
"id": 2,
91
"value": 2,
92
"parent": 1
93
}
94
]
95
}
96
];
97
98
const result = listToTree(received);
99
100
expect(result).toStrictEqual(expected);
101
});
102
});
Copied!
最近更新 10mo ago
复制链接