function toTree(node){
node.forEach(function(it){
delete it.children;
})
// 定义map/
var map = {};
// 这里可以重构数据类型,放回字段值
node.forEach(function(it){
map[it.id]=it;
})
// 定义返回集合
var val=[];
node.forEach(function(it){
var parent = map[it.pid];
if(parent){
// 有数据说明不是顶级节点,将数据放到该 children 子节点下
((parent.children) || (parent.children=[])).push(it);
}else{
// 没有数据说明是顶级节点放到val中
val.push(it);
}
});
return val;
}
console.log(JSON.stringify(toTree(node)))
js 通过id和pid 遍历树结构
于 2022-05-19 12:24:14 首次发布