js 通过id、pid遍历集合获得树结构
原文章地址
node=[{id:1,pid:0,name:"吉林省"},
{id:2,pid:1,name:"长春市"},
{id:3,pid:1,name:"松原市"},
{id:4,pid:0,name:"辽宁省"},
{id:5,pid:4,name:"沈阳市"},
{id:6,pid:3,name:"扶余县"}
]
function toTree(node){
node.forEach(function(it){
delete it.children;
})
var map = {};
node.forEach(function(it){
map[it.id]=it;
})
var val=[];
node.forEach(function(it){
var parent = map[it.pid];
if(parent){
((parent.children) || (parent.children=[])).push(it);
}else{
val.push(it);
}
});
return val;
}
console.log(JSON.stringify(toTree(node)))``