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));
原文地址:https://www.cnblogs.com/flamestudio/p/12090848.html
时间: 2024-11-09 00:09:13