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
| const _arr = [
{
id: 1,
data: 1,
pid: "",
},
{
id: 2,
data: 2,
pid: "",
},
{
id: 3,
data: 3,
pid: "1",
},
{
id: 4,
data: 4,
pid: "2",
},
{
id: 5,
data: 5,
pid: "2",
},
];
// 做个_arr字典
let b = 0;
const map = {};
while (b < _arr.length) {
map[_arr[b].id] = _arr[b];
b++;
}
console.log(map);
// map打印结果
/*
{ '1': { id: 1, data: 1, pid: '' },
'2': { id: 2, data: 2, pid: '' },
'3': { id: 3, data: 3, pid: '1' },
'4': { id: 4, data: 4, pid: '2' },
'5': { id: 5, data: 5, pid: '2' } }
*/
const val = [];
for (let i = 0; i < _arr.length; i++) {
const parent = map[Number(_arr[i].pid)]; // 使用字典获取pid获取对应的父级目录数据
if (parent) {
(parent.children || (parent.children = [])).push(_arr[i]);
// 简化内容
/*
if(parent.children){
parent.children.push(_arr[i])
}else{
parent.children = []
parent.children.push(_arr[i])
}
*/
} else {
val.push(_arr[i]);
}
}
val[0].data = "sdsd"; // 修改整理后数据
console.log(map);
console.log(_arr);
console.log(val);
/*
map
{ '1': { id: 1, data: 'sdsd', pid: '', children: [ [Object] ] },
'2':
{ id: 2, data: 2, pid: '', children: [ [Object], [Object] ] },
'3': { id: 3, data: 3, pid: '1' },
'4': { id: 4, data: 4, pid: '2' },
'5': { id: 5, data: 5, pid: '2' } }
_arr
[ { id: 1, data: 'sdsd', pid: '', children: [ [Object] ] },
{ id: 2, data: 2, pid: '', children: [ [Object], [Object] ] },
{ id: 3, data: 3, pid: '1' },
{ id: 4, data: 4, pid: '2' },
{ id: 5, data: 5, pid: '2' } ]
val
[ { id: 1, data: 'sdsd', pid: '', children: [ [Object] ] },
{ id: 2, data: 2, pid: '', children: [ [Object], [Object] ] } ]
*/
/*
val[0].data = "sdsd"
可以看到map、_arr、val都受到影响,说明他们是同一份数据
map['1'] 因为'1': { id: 1, data: 1, pid: '' }
是一个对象,对象是引用类型,所以val[0].data修改的是同一份数据
*/
|