做前端的经常会遇到要将数组转化成树状结构,这个写起来比较容易出错,故在此将代码奉上,减少开发时间
<!DOCTYPE html>
<html>
<body>
<pre>
节点1
节点2
节点3
节点4
节点5
节点6
</pre>
<script type="text/javascript">
var data=[{nodeId:1,label:'节点1'},{nodeId:2,label:'节点2',parentId:1},{nodeId:3,label:'节点3',parentId:1},{nodeId:4,label:'节点4',parentId:3},{nodeId:5,label:'节点5'},{nodeId:6,label:'节点6',parentId:5},];
function getTree(treeData){
if(treeData==undefined||treeData.length==0)
return;
var firstMenus=[];
var leftMenus=[];//剩余未处理的
var dealData=deepCopy(treeData);
for(var i in dealData){
if(dealData[i].parentId==undefined||dealData[i].parentId==''){
firstMenus.push(dealData[i]);
}else{
leftMenus.push(dealData[i]);
}
}
buildMenuTree(firstMenus,leftMenus);
return firstMenus;
}
function buildMenuTree(firstMenus, leftMenus) {
var deleteNode={};//待删除节点
for (var i in firstMenus) {
for (var j in leftMenus) {
if (firstMenus[i].nodeId === leftMenus[j].parentId) {
if (firstMenus[i].children == undefined) {
firstMenus[i].children = [leftMenus[j]];
} else {
firstMenus[i].children.push(leftMenus[j]);
}
deleteNode[leftMenus[j].nodeId]='';
}
}
}
//删除已经处理的
for(var i in leftMenus){
if(deleteNode[leftMenus[i].nodeId]){
leftMenus.splice(i, 1);//移除已处理的元素
}
}
//处理children的层级,剩余未处理的
for (var k in firstMenus) {
if (firstMenus[k].children != undefined && firstMenus[k].children.length > 0) {
buildMenuTree(firstMenus[k].children, leftMenus);
}
}
}
//深拷贝,注意简单的slice是无法真正的进行深拷贝的,children属性无法去除,多次执行getTree方法就可出现bug
function deepCopy(ary){
return JSON.parse(JSON.stringify(ary));
}
console.log(getTree(data));
</script>
</body>
</html>
控制台输出
即