手记

js递归实现数组转树结构(多级菜单应用)

网上引用的:

 function fn(data, pid) {
    var result = [], temp;
    for (var i = 0; i < data.length; i++) {
        if (data[i].pid == pid) {
            var obj = {"text": data[i].name,"id": data[i].id};
            temp = fn(data, data[i].id);
            if (temp.length > 0) {
                obj.children = temp;
            }
            result.push(obj);
        }
    }
    return result;
}

自己写的

var aaa= [{name:'aaa',id:0},{name:'a',id:1},{name:'b',id:2,pid:1},{name:'c',id:3,pid:1},{name:'d',id:4,pid:2},{name:'e',id:5,pid:2}];

function test(ary,data){

    var data=data?data:(function(ary){
      var tempAry=[];
      for(var i=0,len=ary.length;i<len;i++){
        if(!!ary[i].pid==false){
          var obj={name:ary[i].name,id:ary[i].id};
          tempAry.push(obj);
        }
       }
        return tempAry; 
    }(ary));

    var temp=0;
   if(data.constructor==Array){
     for(var i=0,len=data.length;i<len;i++){
        for(var j=0,lenA=ary.length;j<lenA;j++){
           if(ary[j].pid==data[i].id){
           var obj={name:ary[j].name,id:ary[j].id};
           data[i].child=data[i].child||[];
           data[i].child.push(obj);
           temp++;
       }
     }
    }
   }

   if(temp>0){
     if(data.constructor==Array){
      for(var n=0,lenB=data.length;n<lenB;n++){
        data[n].child=test(ary,data[n].child?data[n].child:[]);
        if(data[n].child.length==0){
            delete data[n].child;
        }
          delete data[n].id;
      } 
    }
   }else{
       for(var n=0,lenB=data.length;n<lenB;n++){
          delete data[n].id;
       } 

   }
    return data;

}
var a=test(aaa);
    console.log(a)
2人推荐
随时随地看视频
慕课网APP