示例代码
const arr = [
{ 'id': '29', 'pid': '', 'name': '总裁办' },
{ 'id': '2c', 'pid': '', 'name': '财务部' },
{ 'id': '2d', 'pid': '2c', 'name': '财务核算部'},
{ 'id': '2f', 'pid': '2c', 'name': '薪资管理部'},
{ 'id': 'd2', 'pid': '', 'name': '技术部'},
{ 'id': 'd3', 'pid': 'd2', 'name': 'Java研发部'},
{ 'id': 'd4', 'pid': 'd3', 'name': 'Java研发部-1组'}
]
// 在list找pid为第二次参数的元素,组成一个数组
function findChildren(list, pid) {
// 在list中根据pid来找元素
let treeList = []
treeList = list.filter(item => item.pid === pid)
console.log(treeList);
/**
* [
* { 'id': '29', 'pid': '', 'name': '总裁办',children:[] },
* { 'id': '2c', 'pid': '', 'name': '财务部' },
* { 'id': 'd2', 'pid': '', 'name': '技术部'}
* ]
* */
treeList.forEach(item => {
item.children = findChildren(list, item.id)
})
return treeList
输出结果
总结:
从打印结果可以看出递归代码很少,每一次都遍历一遍,如果数据多的话就是比较耗性能的