// 把后端传过来的平铺数组数据处理为tree组件需要的树形数据
//方法1
export function tranListToTreeData(list) {
const treeList = []
const map = {}
list.forEach(item => {
item.children = []
map[item.id] = item
})
list.forEach(item => {
const parent = map[item.pid]
if (parent) {
parent.children.push(item)
} else {
treeList.push(item)
}
})
return treeList
}
//方法2
利用递归数组转树
export function tranListToTreeData(list, rootId = '') {
const children = []
list.forEach(item => {
if (item.pid === rootId) {
children.push(item)
// item.children继续执行这个函数(递归),找item.children的儿子
item.children = tranListToTreeData(list, item.id)
}
})
return children
}