Skip to content

树转数组/数组转树

树转数组

将一个嵌套的树结构转换为一个数组,数组中的每个元素都是树的一个节点。

代码展示
js
// 树转数组
// 递归实现
const treeToArray = (tree) => {
    let arr = []
    tree.forEach(item => {
        arr.push(item)
        if (item.children)
            arr = [...arr, ...treeToArray(item.children)]
    })
    return arr
}
// 非递归实现
const treeToArray = (tree) => {
    let arr = []
    let stack = [...tree]
    while (stack.length) {
        let item = stack.shift()
        arr.push(item)
        if (item.children)
            stack = [...item.children, ...stack]
    }
    return arr
}

数组转树

将一个数组转换为一个嵌套的树结构,数组中的每个元素都是树的一个节点。

代码展示
js
// 数组转树
// 递归实现
const arrayToTree = (arr) => {
    let tree = []
    arr.forEach(item => {
        if (item.parentId === 0)
            tree.push(item)
        else {
            let parent = arr.find(parent => parent.id === item.parentId)
            if (parent)
                parent.children = parent.children || []
                parent.children.push(item)
        }
    })
    return tree
}

// 浅拷贝实现
const arrayToTree = (arr) => {
    let tree = []
    let map = {}
    arr.forEach(item => {
        map[item.id] = item
    })
    arr.forEach(item => {
        if (item.parentId === 0)
            tree.push(item)
        else {
            let parent = map[item.parentId]
            if (parent)
                parent.children = parent.children || []
                parent.children.push(item)
        }
    })
    return tree
}