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