数组和树的互相转换
数组转树
let arr = [
{ 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 },
]
function arrayToTree(items) {
const result = []
const itemMap = {}
for (const item of items) {
itemMap[item.id] = { ...item, children: [] }
}
for (const item of items) {
const id = item.id
const pid = item.pid
const treeItem = itemMap[id]
if (pid === 0) {
result.push(treeItem)
} else {
itemMap[pid].children.push(treeItem)
}
}
return result
}
const getChildren = (data, children, pid) => {
for (const item of data) {
if (item.pid === pid) {
const newItem = { ...item, children: [] }
children.push(newItem)
getChildren(data, newItem.children, item.id)
}
}
}
const arrayToTree2 = (data, pid) => {
const result = []
getChildren(data, result, pid)
return result
}
arrayToTree(arr)
arrayToTree2(arr, [], 0)
树转数组
const tree = {
id: 1,
name: '部门1',
pid: 0,
children: [
{
id: 2,
name: '部门2',
pid: 1,
children: [],
},
{
id: 3,
name: '部门3',
pid: 1,
children: [
{
id: 4,
name: '部门4',
pid: 3,
children: [
{
id: 5,
name: '部门5',
pid: 4,
children: [],
},
],
},
],
},
],
}
function treeToArray(tree) {
const result = []
function flatChildren(node) {
const { id, name, pid } = node
result.push({ id, name, pid })
for (let i = 0; i < node.children.length; i++) {
flatChildren(node.children[i])
}
}
flatChildren(tree)
return result
}
treeToArray(tree)