扁平化数组转换为树状结构(TreeList)

255 阅读1分钟

将扁平化数组转换为树状结构

const originList = [{
    id: 1,
    name: '菜单1',
    parent: null,
}, {
    id: 11,
    name: '菜单1-1',
    parent: 1,
}, {
    id: 12,
    name: '菜单1-2',
    parent: 1,
}, {
    id: 2,
    name: '菜单2',
    parent: null,
}, {
    id: 21,
    name: '菜单2-1',
    parent: 2,
}, {
    id: 22,
    name: '菜单2-2',
    parent: 2,
}, ]

function getTreeList(originList, parent, targetList) {
    for (let i of originList) {
        if (i.parent === parent) {
            targetList.push(i)
        }
    }

    for (let i of targetList) {
        i.children = []
        // 递归处理
        getTreeList(originList, i.id, i.children)
        // 如果没有子节点,删除children属性
        if (i.children.length === 0) {
            delete i.children
        }
    }
}

const targetList = []
getTreeList(originList, null, targetList)
console.log('targetList', JSON.stringify(targetList))

得到的树状结构结果为

[{
    "id": 1,
    "name": "菜单1",
    "parent": null,
    "children": [{
        "id": 11,
        "name": "菜单1-1",
        "parent": 1
    }, {
        "id": 12,
        "name": "菜单1-2",
        "parent": 1
    }]
}, {
    "id": 2,
    "name": "菜单2",
    "parent": null,
    "children": [{
        "id": 21,
        "name": "菜单2-1",
        "parent": 2
    }, {
        "id": 22,
        "name": "菜单2-2",
        "parent": 2
    }]
}]