js实现无限层级树形数据结构 组装树形结构,含 反向扁平化

/*
* 组装树形函数 (树形有无限层级)
* 根据parent_id 将数据组装到每个元素children属性当中 parent_id = 0 为最顶级元素
*/

 

/*
 * js实现无限层级树形数据结构(创新算法)
 * 根据parent_id 将数据组装到每个元素children属性当中 parent_id = 0 为最顶级元素
 * Note: 把扁平数据转成树形数据
 */

const data = [
    { id: 1, name: '模块1', parent_id: 0, children: [] },
    { id: 2, name: '子模块1-1', parent_id: 1, children: [] },
    { id: 3, name: '子模块1-2', parent_id: 1, children: [] },
    { id: 4, name: '模块3', parent_id: 0, children: [] },
    { id: 5, name: '子模块3-1', parent_id: 4, children: [] },
    { id: 6, name: '子模块1-2-1', parent_id: 3, children: [] },
];

function getNestedChildren(arr, parent) {
    const res = [];
    for (let item of arr) {
        if (item.parent_id === parent) {
            const children = getNestedChildren(arr, item.id);
            if (children.length) {
                item.children = children;
            }
            res.push(item);
        }
    }
    return res;
}

const arr = [
    {
        id: 1,
        name: '模块1',
        parent_id: 0,
        children: [
            { id: 2, name: '子模块1-1', parent_id: 1, children: [] },
            {
                id: 3,
                name: '子模块1-2',
                parent_id: 1,
                children: [{ id: 6, name: '子模块1-2-1', parent_id: 3, children: [] }],
            },
        ],
    },
    { id: 4, name: '模块3', parent_id: 0, children: [{ id: 5, name: '子模块3-1', parent_id: 4, children: [] }] },
];

// 反向操作
function getFlattenChildren(arr = []) {
    let res = [];
    arr.forEach(item => {
        res.push(item);
        if (item.children) {
            res.push(...helper(item.children));
        }
    });
    return res;
}

 

posted @ 2021-07-07 18:24  Bruce_Grace  阅读(1457)  评论(0编辑  收藏  举报