第一种:
// 把后端传过来的平铺数组数据处理为tree组件需要的树形数据
export function tranListToTreeData(list) {
// 定义两个变量 一个用于接收新数据,一个用于把对象象变为键值关系
const listTree = [] // 一个新的数组
const map = {} // 一个转换对象
// 循环遍历
list.forEach((item) => {
// console.log(item)
// 应为建立树形结构需要children属性,所以判断item中是否存在children,如果不存在,就要添加
if (!item.children) {
item.children = []
}
// 映射关系: 目的是让我们能通过id快速找到对应的元素
map[item.id] = item
})
// console.log(map)
list.forEach((item) => {
const p = map[item.pid]
// console.log(map,item.id)
// console.log(p)
// 判断是否存在父级,如果存在就放进父级的children数组中,如果不存在就放入listTree中
if (p) {
p.children.push(item)
} else {
listTree.push(item)
}
})
return listTree
}
第二种:递归
// rootValue 在第一个时传递的是一级的 pid ''; 在递归时 传入的当前项的 id
function transTree(list, rootValue) {
const treeData = []
// 开始对数组进行遍历
list.forEach(item => {
// 如果是一级 进入if 中查找2级
if (item.pid === rootValue) {
// 第一个参数: 既然是查找2级 是对 list中每一项进行查找
// 第二个参数: 是当前遍历这一项的id
const children = transTree(list, item.id)
if (children.length) {
item.children = children
}
treeData.push(item)
}
})
return treeData
}