树
一、
let dataInfo = res.data || []
let setTree = []
dataInfo.forEach(item => {
if (item.level === 1 || item.level === 2) {
const parent = dataInfo.find((node) => node.id === item.pid)
if (parent) {
parent.children = parent.children || []
parent.children.push(item)
} else {
setTree.push(item)
}
}
})
二、
// * 先生成parent建立父子关系
const obj = {}
dataInfo.forEach((item) => {
obj[item.id] = item
});
const parentList = []
dataInfo.forEach((item) => {
const parent = obj[item.pid]
if (parent) {
// * 当前项有父节点
parent.children = parent.children || []
parent.children.push(item)
} else {
// * 当前项没有父节点 -> 顶层
parentList.push(item)
}
})
console.log(parentList)