JavaScript中数组转树形结构(利用递归)的转换代码
代码如下
const dataList = [{
id: 1,
name: '技术部'
}, {
pid: 1,
id: 11,
name: '前端技术部'
}, {
pid: 11,
id: 111,
name: '小程序技术部'
}, {
pid: 11,
id: 112,
name: 'Vue技术部'
}, {
pid: 1,
id: 12,
name: 'Java技术部'
}, {
pid: 1,
id: 13,
name: 'Python技术部'
}, {
id: 2,
name: '运营部'
}, {
pid: 2,
id: 21,
name: '济南运营部'
}, {
pid: 2,
id: 22,
name: '青岛运营部'
}, {
id: 3,
name: '行政部'
}]
const list2tree = (list, pid) => {
// 存储结果的树形数组
const arr = []
// 遍历list数组
list.forEach((item) => {
// 查找一级结构
if (item.pid === pid) {
// 查找二级甚至是多级结构
// 函数递归,查找item的子结构
const children = list2tree(list, item.id)
// 如果children不为空,说明item有子结构
if (children.length) {
// 需要给item添加children属性
item.children = children
}
// 添加一级结构到结果树形数组中
arr.push(item)
}
})
// 返回结果的树形数组
return arr
}
const result = list2tree(dataList)
console.log(result);
控制台输出为:
以上内容均为笔记,如对您有效还望点赞,谢谢