对于很多收到的数据,我们都需要转换为树菜单的结构
一般这类数据都有一定顺序
下面的测试数据就是后台发给前台的数据
pid 和 subgroup_id 对应着他们的关系
你可以替换为你的对应关系,对应的字段当然也需要修改
包括结构push进去的对象要是当前数据的
通过判断data长度是否为空的死循环来控制生成树结构
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="Access-Control-Allow-Origin" content="*"> <title>Title</title> </head> <body> <!--startprint--> <p>F12打开控制台查看</p> 数据: <pre> {subgroup_id:1,pid:0,text:'A'}, {subgroup_id:2,pid:4,text:"E[父C]"}, {subgroup_id:3,pid:7,text:"G[父F]"}, {subgroup_id:4,pid:1,text:"C[父A]"}, {subgroup_id:5,pid:6,text:"D[父B]"}, {subgroup_id:6,pid:0,text:'B'}, {subgroup_id:7,pid:4,text:"F[父C]"}, {subgroup_id:8,pid:3,text:"z[父G]"} </pre> <script> (function () { var datas=[ {subgroup_id:1,pid:0,text:'A'}, {subgroup_id:2,pid:4,text:"E[父C]"}, {subgroup_id:3,pid:7,text:"G[父F]"}, {subgroup_id:4,pid:1,text:"C[父A]"}, {subgroup_id:5,pid:6,text:"D[父B]"}, {subgroup_id:6,pid:0,text:'B'}, {subgroup_id:7,pid:4,text:"F[父C]"}, {subgroup_id:8,pid:3,text:"z[父G]"} ]; function toTreeData(data){ var pos={}; var tree=[]; var i=0; while(data.length!=0){ if(data[i].pid==0){ tree.push({ subgroup_id:data[i].subgroup_id, text:data[i].text, //children:[] //无孩子无节点 }); pos[data[i].subgroup_id]=[tree.length-1]; data.splice(i,1); i--; }else{ var posArr=pos[data[i].pid]; if(posArr!=undefined){ var obj=tree[posArr[0]]; for(var j=1;j<posArr.length;j++){ obj=obj.children[posArr[j]]; } //有孩子有节点 if(obj.children){}else{ obj.children = []; } obj.children.push({ subgroup_id:data[i].subgroup_id, text:data[i].text, //children:[] //无孩子无节点 }); pos[data[i].subgroup_id]=posArr.concat([obj.children.length-1]); data.splice(i,1); i--; } } i++; if(i>data.length-1){ i=0; } } return tree; } console.log(toTreeData(datas)) })(); </script>
</body> </html>