一维数组转成树结构

46 阅读1分钟
const arrTree = [
    {
        parentId: null,
        id: 0,
    },
    {
        parentId: 0,
        id: 2,
    },
    {
        parentId: 0,
        id: 1,
    },
    {
        parentId: 1,
        id: 3,
    },
    {
        parentId: 2,
        id: 4,
    }
]


function arrToTree(arr) {

    if (!Array.isArray(arr) || arr.length === 0) return {}

    let root = null

    for ( let i = 0; i < arr.length; i++ ) {

        for ( let j = i; j < arr.length; j++ ) {
            
            if (arr[j].parentId === arr[i].id) {
                if (
                    Array.isArray(arr[i].children)
                ) {
                    arr[i].children.push(arr[j])
                } else {
                    arr[i].children = [ arr[j] ]
                }
            }
        }


        if ( arr[i].parentId === null ) root = arr[ i ]
        

    }
    return root

}

console.log(arrToTree(arrTree))