-
Notifications
You must be signed in to change notification settings - Fork 2
/
手写草稿.html
83 lines (76 loc) · 2.19 KB
/
手写草稿.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
var arr = [{
'id': 1,
'parentid': 0
},
{
'id': 4,
'parentid': 2
},
{
'id': 3,
'parentid': 1
},
{
'id': 5,
'parentid': 0
},
{
'id': 6,
'parentid': 0
},
{
'id': 2,
'parentid': 1
},
{
'id': 7,
'parentid': 4
},
{
'id': 8,
'parentid': 1
}
];
function unflatten(arr) {
debugger;
var tree = [],
mappedArr = {},
arrElem,
mappedElem;
// First map the nodes of the array to an object -> create a hash table.
for (var i = 0, len = arr.length; i < len; i++) {
arrElem = arr[i];
mappedArr[arrElem.id] = arrElem;
mappedArr[arrElem.id]['children'] = [];
}
console.log(mappedArr,'-----------mappedArr')
for (var id in mappedArr) {
if (mappedArr.hasOwnProperty(id)) {
console.log(id,'-----------id')
mappedElem = mappedArr[id];
// If the element is not at the root level, add it to its parent array of children.
if (mappedElem.parentid) {
mappedArr[mappedElem.parentid].children.push(mappedElem);
}
// If the element is at the root level, add it to first level elements array.
else {
tree.push(mappedElem);
}
}
}
return tree;
}
var tree = unflatten(arr);
console.log(tree,'...............tree')
</script>
</body>
</html>