项目中总会遇到将很长的一个每项都含有pid、id、xxx等字段的数组
需要将他转化为树形结构,以方便使用
// 方法一 递归 这个方法需要先找到 单独根节点 后面的方法可以有多个根节点
arrayToTree1(arr, parent) {
let tree = []
arr.forEach((item) => {
if (item.pid === parent.id) {
let children = this.arrayToTree(arr, item)
if (children.length > 0) {
item.children = children
}
tree.push(item)
}
})
return tree
},
// 方法二 数组转为对象进行操作 巧妙使用浅拷贝
arrayToTree2(arr) {
let temp = {}
let tree = []
// 数组整理成对象
arr.forEach((item, idx) => {
temp[item.id] = item
})
// 整理成对象 用.调用比较方便
for (let i in temp) {
if (temp[i].pid) {
if (!temp[temp[i].pid].children) {
temp[temp[i].pid].children = []
}
temp[temp[i].pid].children.push(temp[i])
} else {
tree.push(temp[i])
}
}
return tree
},
// 方法三 数组双循环 效率最低 可以优化但没必要 直接用上面的就行
arrayToTree3(arr) {
arr.forEach((fItem, idx) => {
arr.forEach((sItem) => {
if (fItem.id === sItem.pid) {
if (!fItem.children) {
fItem.children = []
}
fItem.children.push(sItem)
}
})
})
return arr.filter((item) => !item.pid)
}