SOURCE

const tree = [
    {
        id: 1,
        name: '1',
        children: [
            {
                id: 2,
                name: '2',
                children: [
                    {
                        id: 3,
                        name: '3'
                    }
                ]
            },
            {
                id: 4,
                name: '4'
            }
        ]
    },
    {
        id: 5,
        name: '5'
    }
]

const fn1 = (tree) => {
    let res = []
    let stack = []
    let path = ''
    stack.push({ tree, path: '' })
    while (stack.length) {
        const stackItem = stack.pop()
        const node = stackItem.tree
        const path = stackItem.path
        for (let item in node) {
            let nodeRes = JSON.parse(JSON.stringify(node[item]))
            delete nodeRes.children
            nodeRes.path = path || '0'
            res.push(nodeRes)
            if (node[item].children) {
                stack.push({ tree: node[item].children, path: nodeRes.id })
            }
        }
    }
    return res
}

const fn2 = (tree, path = '0') => {
    let res = []
    for (let i in tree) {
        let nodeRes = JSON.parse(JSON.stringify(tree[i]))
        delete nodeRes.children
        nodeRes.path = path
        res.push(nodeRes)
        if (tree[i].children) {
            res = res.concat(fn2(tree[i].children, tree[i].id))
        }
    }
    return res
}

// console.log(fn2(tree))

// 扁平化转树结构
const arr = [{ "id": 1, "name": "1", "path": "0" }, { "id": 2, "name": "2", "path": 1 }, { "id": 3, "name": "3", "path": 2 }, { "id": 4, "name": "4", "path": 1 }, { "id": 5, "name": "5", "path": "0" }]

const fn3 = (arr) => {
    let res = []
    let map = {}
    for (let i in arr) {
        map[arr[i].id] = arr[i]
    }

    for (let i in arr) {
        if (arr[i].path == '0') {
            res.push(arr[i])
        } else {
            if (map[arr[i].path].children) {
                map[arr[i].path].children.push(arr[i])
            } else {
                map[arr[i].path].children = [arr[i]]
            }
        }
    }
    return res
}
console.log(fn3(arr))
console 命令行工具 X clear

                    
>
console