js實現線性結構轉樹形結構(生成無限層級菜單)


let list = [ 
    { parentId: 0, id: 1, value: '1' },
    { parentId: 3, id: 2, value: '2' }, 
    { parentId: 0, id: 3, value: '3' },
    { parentId: 1, id: 4, value: '4' }, 
    { parentId: 1, id: 5, value: '5' }, 
]; 

function listToTree(list){
    //遍歷整個列表
    return list.filter(cur=>{ 
        // 獲取當前節點的子節點
        let children= list.filter(item=> item.parentId == cur.id ); 
        if(children.length>0){
             cur.children=children;
        }
        //只返回頂級節點
        return cur.parentId==0; 
    });
}

console.log(listToTree(list));


免責聲明!

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



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