根据js对象的浅拷贝来实现数组的自我递归调用来实现数据排序 排序前图
排序后图
代码直接贴上,喜欢研究的自己可以研究下,很有意思的。
代码语言:javascript复制<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>根据对象的浅拷贝来实现对数组的排序</title>
</head>
<body>
<script src="sortJson.js"></script>
<script>
console.log(tJson);
var sortObj = arrayToJson(tJson);
console.log(sortObj);
function arrayToJson(treeArray){
let ary = [];
let tmpMap ={};
for (let i=0, l=treeArray.length; i<l; i ) {
tmpMap[treeArray[i]["id"]]= treeArray[i];
}
for (let i=0, l=treeArray.length; i<l; i ) {
let key=tmpMap[treeArray[i]["parentId"]];
treeArray[i].index = i '';
treeArray[i].name = treeArray[i].powerName;
treeArray[i].url = treeArray[i].powerCode;
if (key) {
if (!key["children"]){
key["children"] = [];
key["children"].push(treeArray[i]);
}else{
key["children"].push(treeArray[i]);
}
console.log(key);
} else {
ary.push(treeArray[i]);
}
}
return ary
}
</script>
</body>
</html>
链接:https://pan.baidu.com/s/1h8lHHvn9G1MjmdEw_TGqdA 提取码:pfwz