js 递归组装树形结构

随记。

  1. 有时候就是会遇到这样的情况,需要前端组成树形结构;
  2. 以下随意看看,整理随记。
<!DOCTYPE html>
<html>
<head>
<script>
var treeData=[
{"id":"inter","parentId":"product","spType":0,"layerId":0,"seqId":1,"name":"网络产品","deleted":"0"},
{"id":"product","parentId":"","spType":0,"layerId":0,"seqId":50,"name":"产品中心","deleted":"0"},
{"id":"online","parentId":"product","spType":0,"layerId":0,"seqId":2,"name":"线上产品","deleted":"0"},
{"id":"unline","parentId":"product","spType":0,"layerId":0,"seqId":3,"name":"线下产品","deleted":"0"},
{"id":"update","parentId":"dispatch","spType":0,"layerId":0,"seqId":1,"name":"关于产品更新","deleted":"0"},
{"id":"dispatch","parentId":"","spType":0,"layerId":0,"seqId":2,"name":"通知公告","deleted":"0"},
{"id":"diedai","parentId":"dispatch","spType":0,"layerId":0,"seqId":2,"name":"产品迭代","deleted":"0"},
{"id":"address","parentId":"about","spType":0,"layerId":0,"seqId":1,"name":"公司地址","deleted":"0"},
{"id":"about","parentId":"","spType":0,"layerId":0,"seqId":1,"name":"关于我们","deleted":"0"},
{"id":"portals","parentId":"","spType":0,"layerId":0,"seqId":3,"name":"门户管理","deleted":"0"},
{"id":"communication","parentId":"address","spType":0,"layerId":0,"seqId":1,"name":"联系我","deleted":"0"},
];
  var getTree=function(treeData,parentId){
       var treeArr=[];
       for(var i=0;i<treeData.length;i++){ 
           var node=treeData[i];
            if(node.parentId==parentId ){ 
               var newNode={id:node.id,title:node.name,children:getTree(treeData,node.id)};
               treeArr.push(newNode);              
            }
       }
       return treeArr;
   }
   console.log(getTree(treeData,''));
    
</script>
</head>
<body>
</body>
</html>

你可能感兴趣的:(javascript)