当前位置: 首页 > Web前端 > JavaScript

无需递归生成无限层树

时间:2023-03-27 16:23:34 JavaScript

偶然在技术群里聊到生成无限层次树的老话题,于是记录下n年前一次生成无限层次树的解决方案业务场景,涉及全国行政区、省市的树,最小的颗粒去医院。后台返回的分片数据大小超过1M。前端处理完数据再渲染,卡顿很明显。后端返回的数据结构[{"id":1,"name":"中华人民共和国","parentId":0,},{"id":1001,"name":"浙江省","parentId":1,},{"id":2001,"name":"杭州市","parentId":1001,},{"id":3001,"name":"西湖区","parentId":2001,},{"id":4001,"name":"杭州市第一人民医院","parentId":3001,},//其他省略]第一版:递归处理树常规处理方法//咯,网上抢一把第二版:非递归处理树改进版处理方法constbuildTree=(itemArray,{id='id',parentId='parentId',children='children',topLevelId='0'}={})=>{returnitemArray.filter((item)=>{//挂载子级item[children]=itemArray.filter((child)=>String(item[id])===String(child[parentId]));//返回顶级数据returnString(item[parentId])===topLevelId;});};时间复杂度:O(n^2)第三版:非递归处理树import{groupBy}from'lodash';constbuildTree=(itemArray,{id='id',parentId='parentId',children='children',topLevelId='0'}={})=>{constparentObj=groupBy(itemArray,parentId)returnitemArray.filter((item)=>{//挂载子级别item[children]=parentObj[item[id]];//返回顶级数据returnString(item[parentId])===topLevelId;});};时间复杂度:O(2n)最终版本:非递归处理树constbuildTree=(itemArray,{id='id',parentId='parentId',children='children',topLevelId='0'}={})=>{constparentMap=newMap();//临时存储所有父级consttopLevelResult=[];//存储顶级结果for(letitemofitemArray){if(!parentMap.has(item[id])){item[children]=[]}else{item[children]=parentMap.get(item[id]])[孩子们];}parentMap.set(item.id,item)if(!parentMap.has(item[parentId])){parentMap.set(item[parentId],{[children]:[]});}parentMap.get(item[parentId])[children].push(item)if(String(item[parentId])===String(topLevelId)){topLevelResult.push(item)}}returntopLevelResult;}时间复杂度:O(n)下一部分共享无限层次树的交集,无需递归

最新推荐
猜你喜欢