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;
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM