线性结构转树形结构(生成无限层级菜单)

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

猜你喜欢

转载自www.cnblogs.com/flamestudio/p/12090848.html