扁平结构转树形结构
方法1:使用数组与对象
function arrayToTree(arr) {
const map = {}
const tree = []
arr.forEach(item => {
map[item.id] = { ...item, children: [] }
})
arr.forEach(item => {
if (item.parentId !== 0) {
map[item.parentId].children.push(map[item.id])
} else {
tree.push(map[item.id])
}
})
return tree
}
方法2:递归
function buildTree(data, parentId = 0) {
const tree = []
data
.filter(item => item.parentId === parentId)
.forEach(item => {
const children = buildTree(data, item.id)
if (children.length) {
item.children = children
}
tree.push(item)
})
return tree
}
树形结构转扁平结构
递归
function treeToFlat(tree, parentId = 0, result = []) {
tree.forEach(node => {
const { id, name, code, children, remark } = node
result.push({ id, name, code, parentId, remark })
if (children) {
treeToFlat(children, id, result)
}
})
return result
}
迭代
function treeToFlat(tree) {
const stack = [...tree] // 栈数据结构来模拟迭代
const result = []
while (stack.length) {
const node = stack.pop()
const { id, name, code, parentId, remark, children } = node
result.push({ id, name, code, parentId, remark })
if (children) {
for (let i = children.length - 1; i >= 0; i--) {
const child = children[i]
child.parentId = id
stack.push(child)
}
}
}
return result
}