let arr = [
{id:1,name:"php",pid:0},
{id:2,name:"php基础",pid:1},
{id:3,name:"php面向对象",pid:1},
{id:4,name:"python",pid:0},
{id:5,name:"python迭带器",pid:4},
{id:6,name:"python面向对象",pid:4},
{id:7,name:"python网络编程",pid:4},
];
// 查询一级分类
function findChild(arr,id) {
let childs = [];
arr.forEach(v=>{
if (v.pid == id){
childs.push(v);
}
});
return childs;
}
//
function build_tree(id) {
let childs= findChild(arr,id);
if (childs.length==0){
return null;
}
// 对于父节点为0的进行循环,然后查出父节点为上面结果id的节点内容
childs.forEach((v,k)=>{
let buildTree = build_tree(v.id);
if (null != buildTree){
v['children'] = buildTree;
}
});
return childs;
}
console.log(build_tree(0));
转载于:https://www.cnblogs.com/leigepython/p/10301401.html