id,pid数组转拓扑树结构

 var source = [
   
     { id:1,pid:0,value:"节点1" },
     { id:2,pid:1,value:"节点11" },
     { id:3,pid:1,value:"节点12" },
     { id:4,pid:1,value:"节点13" },
     { id:5,pid:0,value:"节点2" },
     { id:6,pid:5,value:"节点21" },
     { id:7,pid:5,value:"节点22" },
     { id:8,pid:5,value:"节点23" },
     { id:9,pid:0,value:"节点3" },
     { id:10,pid:9,value:"节点31" },
     { id:11,pid:10,value:"节点32" },
     { id:12,pid:11,value:"节点33" },
     { id:13,pid:12,value:"节点34" },
     { id:14,pid:13,value:"节点35" },
     { id:15,pid:14,value:"节点36" },
     { id:16,pid:0,value:"节点4" }
   
   ]
     function toTree(data) {
       let result = []
       if (!Array.isArray(data)) {
         return result
       }
       data.forEach(item => {
           delete item.children;
       });
       let map = {};
       data.forEach(item => {
           map[item.id] = item;
       });
       data.forEach(item => {
         let parent = map[item.pid];
         if (parent) {
             (parent.children || (parent.children = [])).push(item);
         } else {
             result.push(item);
         }
       });
       return result;
     }
     console.log(toTree(source))

 

 
posted @ 2020-08-26 15:10  键盘敲飞  阅读(400)  评论(0编辑  收藏  举报