数据格式:

        var data = [
             {id: 1, name: 'zs', pid: 0},
             {id: 2, name: 'ls', pid: 0},
             {id: 3, name: 'ww', pid: 0},
             {id: 4, name: 'zs-1',pid: 1},
             {id: 5, name: 'ls-1',pid: 2},
             {id: 6, name: 'ww-1',pid: 3},
             {id: 7, name: 'zs-1-1',pid: 4},
             {id: 8, name: 'ls-1-1',pid: 5},
             {id: 9, name: 'ww-1-1',pid: 6},
             {id: 10, name: 'ml',pid: 0}
        ]

 

把普通数组转成树型结构数据:

function getTree(list,pid){
    var fun = function(pid){
          var pid = pid ? pid : 0;
          var b = [];
          for(var i in list){
              var item = list[i];
              if (item.pid === pid) {
                  item.children = arguments.callee(item.id);
                  b.push(item);
              }
          }
         return b;
     }
     return fun(pid);
}
var _data = getTree(data,0); 
console.log(_data); //可以指定从哪个id 的数据开始转成树型数据

使用从上面得到树型结构数据,再把树型数据再转成普通数组:

function getArray(data){
    var fun = function(data){
       var a = [];
        for( var i in data){
            var item = data[i];
            var obj = new Object();
            for( var j in item){
                if( j !== 'children'){
                    obj[j] = item[j];
                }
            }
            a.push(obj);
            if( item.children.length > 0 ){
                a = a.concat(arguments.callee(item.children));
            }
       }
       return a;
   }
   var list = fun(data);
   //根据id从小到大排序
   list.sort(function(a,b){
       return a.id - b.id
   })
   return list;
}
var _data1 = getArray(_data);
console.log(_data1);

 该方法在下面模块有有该方法

https://www.npmjs.com/package/@qcnh1920/data-transfer

npm i @qcnh1920/data-transfer

 

posted on 2018-10-11 16:48  浅唱年华1920  阅读(685)  评论(0编辑  收藏  举报