【学习笔记】一维数组与树形结构互相转换

49 阅读1分钟
const flatArray = [
    { id: 1, parentId: null },
    { id: 2, parentId: 1 },
    { id: 3, parentId: 1 },
    { id: 4, parentId: 2 },
    { id: 5, parentId: 2 },
    { id: 6, parentId: 3 }
]

// 从一维数组创建树形结构
function createTree(arr) {
    // 创建哈希表存储节点
    const nodeMap = new Map()
    arr.forEach((node) => nodeMap.set(node.id, { ...node }))

    const tree = []

    arr.forEach((node) => {
        const current = nodeMap.get(node.id)

        delete current.parentId

        if (node.parentId === null) {
            tree.push(current)
        } else {
            const parent = nodeMap.get(node.parentId)
            parent.children = parent.children || []
            parent.children.push(current)
        }
    })
    return tree
}

// 把树形结构转换回一维数组
function flattenTree(tree, parentId = null) {
    const result = []
    tree.forEach((node) => {
        result.push({ id: node.id, parentId })

        if (node.children && node.children.length > 0) {
            result.push(...flattenTree(node.children, node.id))
        }
    })
    return result
}

const treeStructure = createTree(flatArray);
console.log('Tree:', JSON.stringify(treeStructure, null, 2));
const flattened = flattenTree(treeStructure);
console.log('Flattened:', JSON.stringify(flattened, null, 2));