生成Tree的结构

原始数据

    [{  "id":"PEData",
        "name":"PEData",
    },
    {
        "id":"OPT",
        "name":"OPT",
        "parentId":"PEData",
    },
    {
        "id":"OPT1",
        "name":"OPT1",
        "parentId":"PEData",
    
    },
    {
        "id":"OPT-1",
        "name":"OPT-1",
        "parentId":"OPT",
    }]

渲染成Tree结构

class TreeTest{
   constructor(treeData){
       this.tree = treeData || [];
       this.groups = {};
   }
    init(parentId) {
       this.group();    
        return this.getDom(this.groups[parentId]);
    } 
    group(){ //获取用有相同父ID的组,
        for(var i=0;i<this.tree.length;i++){
            if(this.groups[this.tree[i].parentId]){
                this.groups[this.tree[i].parentId].push(this.tree[i]);
                
            }else{
                this.groups[this.tree[i].parentId]=[];
                this.groups[this.tree[i].parentId].push(this.tree[i]);
            
            }
        
     }
     }
     getDom(idArr) { // 通过遍历上面的得到的组,组装成Tree
      if(!idArr){return ''}      
        for(var i=0;i<idArr.length;i++){
             idArr[i].child = this.getDom(this.groups[idArr[i].id]) 
        };
        return idArr;
     }
   
}
let Tree=new TreeTest(arr).init('PEData');

何凯
966 声望174 粉丝

Never too late to learn!