继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

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

甜酒0917
关注TA
已关注
手记 13
粉丝 2
获赞 23

网上引用的:

 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)
打开App,阅读手记
2人推荐
发表评论
随时随地看视频慕课网APP