const arr3 = [
{ 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: 5 },
{ id: 7, name: "部门7", pid: 6 },
]
/**
* 扁平数据结构转树结构数据
* @param arr 扁平数据
* @param topPid 非必填 顶部pid
* @returns 树结构数据
*/
const arr2Tree = (arr3, topPid = undefined) => {
const arrMap = new Map()
const newArr = []
let newTopPid = topPid
if (newTopPid === undefined) {
newTopPid = arr3.sort((a, b) => a.pid - b.pid)[0].pid
}
arr3.forEach((item, index) => {
if (item.pid === newTopPid) {
newArr.push(item)
}
if (!arrMap[item.id]) {
arrMap[item.id] = item
}
if (arrMap[item.pid]) {
if (!arrMap[item.pid].children) {
arrMap[item.pid].children = []
}
arrMap[item.pid].children.push(item)
}
})
return newArr
}
const tree = arr2Tree(arr3)
console.log("tree", tree)
/**
* 树结构数据转扁平结构数据
* @param tree 树结构数据
* @returns 扁平结构数据
*/
const tree2Arr = (tree) => {
const newArr = []
/**
* 递归
*/
const recursive = (arr) => {
arr.forEach((item) => {
newArr.push(item)
if (item.children?.length) {
recursive(item.children)
}
})
}
recursive(tree)
return newArr
}
const newArr = tree2Arr(tree)
console.log("newArr", newArr)
数组与树形结构转换
于 2022-06-08 13:12:35 首次发布