Skip to content

Commit 60e61d1

Browse files
committed
feat: 树转数组
1 parent 8894503 commit 60e61d1

File tree

2 files changed

+118
-1
lines changed

2 files changed

+118
-1
lines changed

index.html

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,6 @@
77
<title>Document</title>
88
</head>
99
<body>
10-
<script src="./面试常见的手写题//05-数组转树.js"></script>
10+
<script src="./面试常见的手写题/06-树转数组.js"></script>
1111
</body>
1212
</html>
+117
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
let originalObj = [
2+
{
3+
id: 1,
4+
name: "键盘专区",
5+
path: "xxx/xxx/xxx.vue",
6+
pid: 0,
7+
icon: "xxxx",
8+
children: [
9+
{
10+
id: 5,
11+
name: "达尔优键盘",
12+
path: "xxx/xxx/xxx.vue",
13+
pid: 1,
14+
icon: "xxxx",
15+
children: [
16+
{
17+
id: 14,
18+
name: "达尔优 children",
19+
path: "xxx/xxx/xxx.vue",
20+
pid: 5,
21+
icon: "xxxx",
22+
children: [
23+
{
24+
id: 15,
25+
name: "达尔优 children children",
26+
path: "xxx/xxx/xxx.vue",
27+
pid: 14,
28+
icon: "xxxx",
29+
},
30+
],
31+
},
32+
],
33+
},
34+
{
35+
id: 6,
36+
name: "腹灵cmk87键盘",
37+
path: "xxx/xxx/xxx.vue",
38+
pid: 1,
39+
icon: "xxxx",
40+
},
41+
],
42+
},
43+
{
44+
id: 2,
45+
name: "鼠标专区",
46+
path: "xxx/xxx/xxx.vue",
47+
pid: 0,
48+
icon: "xxxx",
49+
children: [
50+
{ id: 10, name: "g502", path: "xxx/xxx/xxx.vue", pid: 2, icon: "xxxx" },
51+
{ id: 11, name: "毒奎v2", path: "xxx/xxx/xxx.vue", pid: 2, icon: "xxxx" },
52+
{
53+
id: 12,
54+
name: "雷蛇v3",
55+
path: "xxx/xxx/xxx.vue",
56+
pid: 2,
57+
icon: "xxxx",
58+
children: [
59+
{
60+
id: 13,
61+
name: "雷蛇v3 children",
62+
path: "xxx/xxx/xxx.vue",
63+
pid: 12,
64+
icon: "xxxx",
65+
},
66+
],
67+
},
68+
],
69+
},
70+
{
71+
id: 4,
72+
name: "显卡专区",
73+
path: "xxx/xxx/xxx.vue",
74+
pid: 0,
75+
icon: "xxxx",
76+
children: [
77+
{
78+
id: 7,
79+
name: "七彩虹gtx 1660ti",
80+
path: "xxx/xxx/xxx.vue",
81+
pid: 4,
82+
icon: "xxxx",
83+
},
84+
{
85+
id: 8,
86+
name: "华硕3050ti",
87+
path: "xxx/xxx/xxx.vue",
88+
pid: 4,
89+
icon: "xxxx",
90+
},
91+
{
92+
id: 9,
93+
name: "微星 4090ti",
94+
path: "xxx/xxx/xxx.vue",
95+
pid: 4,
96+
icon: "xxxx",
97+
},
98+
],
99+
},
100+
];
101+
102+
function TreeToArrat(tree) {
103+
// console.log(tree);
104+
let arr = [];
105+
function recursion(tree) {
106+
tree.forEach(item => {
107+
arr.push(item);
108+
item.children && recursion(item.children);
109+
delete item.children;
110+
});
111+
}
112+
113+
recursion(tree);
114+
return arr;
115+
}
116+
117+
console.log(TreeToArrat(originalObj));

0 commit comments

Comments
 (0)