
const arr1 = [
{ id: 1, name: '部门1', pid: 0 }, // 根节点
{ id: 2, name: '部门2', pid: 1 },
{ id: 3, name: '部门3', pid: 1 },
{ id: 4, name: '部门4', pid: 3 },
{ id: 5, name: '部门5', pid: 4 },
{ id: 6, name: '部门6', pid: 0 } // 根节点
]
方法一:
- 将列表型的数据转化成树形数据 => 递归算法 => 自身调用自身 => 一定条件不能一样, 否则就会死循环
- 遍历树形 有一个重点 要先找一个头儿
export function tranListToTreeData(list, rootValue) {
var arr = []
list.forEach(item => {
if (item.pid === rootValue) {
const children = tranListToTreeData(list, item.id)
if (children.length) {
item.children = children
}
arr.push(item)
}
})
return arr
}
方法二
function listToTree(list, pid, tree) {
list.forEach((item) => {
if (item.pid === pid) {
tree.push(item)
}
})
tree.forEach((i) => {
i.children = []
listToTree(list, i.id, i.children)
})
return tree
}