把数组的数据结构改成树形结构。
var aaa = [
{name:"111", id: 1, pId: 0, children: []},
{name:"222", id: 6, pId: 0, children: []},
{name:"b", id: 2, pId: 1, children: []},
{name:"c", id: 3, pId: 1, children: []},
{name:"d", id: 4, pId: 2, children: []},
{name:"d", id: 4, pId: 6, children: []},
]
function Tree(data) {
this.tree = data||[]; //数据
this.groups = {}; //分组
}
Tree.prototype = {
init: function(pid) {
this.group();
var data = this.getData(this.groups[pid]);
return data;
},
group: function () {
for(var i=0; i<this.tree.length; i++){
if(this.groups[this.tree[i].pId]){
this.groups[this.tree[i].pId].push(this.tree[i]);
}else{
this.groups[this.tree[i].pId]=[];
this.groups[this.tree[i].pId].push(this.tree[i]);
}
}
},
getData: function (info) {
if (!info) return;
var children = [];
for (var i = 0; i < info.length; i++) {
var item = info[i];
item.children = item['children'].concat(this.getData(this.groups[item.id]));
children.push(item);
}
return children;
}
}
var d = new Tree(aaa).init(0);
console.log(JSON.stringify(d));
我的主要思路是有两步。
1 分组
将所有pId 相同的数据放入一个数组中,
2 从树形结构的最顶层开始查找(pId = 0)。来根据id 递归查找子集。