主题
数组 & 树
数组转树
js
function arrToTree(arr) {
const map = new Map()
for (const item of arr) {
map.set(item.id, item)
}
const roots = []
for (const item of arr) {
if (item.parent === null) {
roots.push(item)
} else {
const parent = map.get(item.parent)
if (!parent.children) {
parent.children = []
}
parent.children.push(item)
}
}
return roots
}
// --- 测试
const tree = arrToTree([
{ id: 1, value: 1, parent: null },
{ id: 2, value: 2, parent: 1 },
{ id: 3, value: 3, parent: 2 },
{ id: 4, value: 4, parent: 1 },
])
console.log(tree)
// --- 测试树转数组
js
function treeToArr(tree, parent = null, result = []) {
for (const node of tree) {
const { children, ...rest } = node
const flatNode = { ...rest, parent }
result.push(flatNode)
if (children && Array.isArray(children)) {
treeToArr(children, node.id, result)
}
}
return result
}
// --- 测试
const arr = treeToArr([
{
id: 1,
value: 1,
parent: null,
children: [
{
id: 2,
value: 2,
parent: 1,
children: [
{
id: 3,
value: 3,
parent: 2,
},
],
},
{
id: 4,
value: 4,
parent: 1,
},
],
},
])
console.log(arr)
// --- 测试