-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsameToTree.ts
More file actions
67 lines (62 loc) · 1.11 KB
/
sameToTree.ts
File metadata and controls
67 lines (62 loc) · 1.11 KB
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
interface IMenuItem {
id: string // current
pid: string | null // parent id
child?: IMenuItem[]
}
interface IFunc {
(arr: IMenuItem[]): IMenuItem[]
}
const findChild = (arr: IMenuItem[], pid: string) => {
let res = []
for (let i = 0; i < arr.length; ) {
if (arr[i].pid === pid) {
let child = arr.splice(i, 1)[0]
child.child = [...findChild(arr, child.id)]
res.push(child)
} else {
i++
}
}
return res
}
const sameToTree: IFunc = (arr: IMenuItem[]) => {
const finalRes = []
for (let i = 0; i < arr.length; ) {
if (arr[i].pid === null) {
let root = arr.splice(i, 1)[0]
root.child = findChild(arr, root.id)
finalRes.push(root)
} else {
i++
}
}
return finalRes
}
// const data: IMenuItem[] = [
// {
// id: 'A',
// pid: null
// },
// {
// id: 'B',
// pid: 'A'
// },
// {
// id: 'C',
// pid: 'B'
// },
// {
// id: 'F',
// pid: 'A'
// },
// {
// id: 'E',
// pid: 'D'
// },
// {
// id: 'D',
// pid: null
// }
// ]
// console.log(sameToTree(data))
export default sameToTree