//将数据库中通过关联(inner join)查询多张表没有嵌套但有嵌套关系的数据进行处理,得到具有嵌套层级且嵌套的父级二级属性不可重复出现,具体实现如下:// 通过关联查询到数据库的数据(格式):let result=[{cid: 1,coll_name: '一级1',pid: 1,projects_name: '二级1',qpid:1,common_name:'三级1'},{cid: 1,coll_name: '一级1',pid: 1,projects_name: '二级1',qpid:2,common_name:'三级2'},{cid: 1,coll_name: '一级1',pid: 2,projects_name: '二级2',qpid:3,common_name:'三级3'},{cid: 1,coll_name: '一级1',pid: 2,projects_name: '二级2',qpid:4,common_name:'三级4'},{cid: 2,coll_name: '一级2',pid: 3,projects_name: '二级3',qpid:5,common_name:'三级5'},{cid: 2,coll_name: '一级2',pid: 3,projects_name: '二级3',qpid:6,common_name:'三级6'},{cid: 2,coll_name: '一级2',pid: 4,projects_name: '二级4',qpid:7,common_name:'三级7'},{cid: 2,coll_name: '一级2',pid: 4,projects_name: '二级4',qpid:8,common_name:'三级8'}]// 最终要得到的数据格式:let da = [{cid:1,coll_name:'一级1',childp:[{pid:1,projects_name:'二级1',childq:[{qpid:1,common_name:'三级1'},{qpid:2,common_name:'三级2'},]},{pid:2,projects_name:'二级2',childq:[{qpid:3,common_name:'三级3'},{qpid:4,common_name:'三级4'},]}]},{cid:2,coll_name:'一级2',childp:[{pid:3,projects_name:'二级3',childq:[{qpid:5,common_name:'三级5'},{qpid:6,common_name:'三级6'},]},{pid:4,projects_name:'二级4',childq:[{qpid:7,common_name:'三级7'},{qpid:8,common_name:'三级8'},]}]}]// 完成实现:// 最终数据存放容器let datalist = []// 存一级cid的数组(找到所有不重复的一级菜单cid)let cidarr = [...new Set(result.map(it => it.cid))]// 处理一级菜单的数据:通过遍历循环不重复的一级菜单cidarr数组生成一级菜单数据,遍历cidarr可确定有几个一级菜单项cidarr.forEach((cid,ci)=>{// 生成一级菜单项:let cobj = {} // 一级菜单对象let carr = [] // 从原数据result中找到cid等于当前遍历的一级菜单的cid值的数据result.map(item=>{ // 找出result中cid等于一级cid数组中每项值的数据并存到carr中if(item.cid===cid){carr.push(item)}})cobj.cid = cid // 生成一级菜单项的cidcobj.coll_name = carr[0].coll_name // 生成一级菜单项的coll_name// 处理一级中的二级菜单属性的值:let pchildtemp = [] // 存当前一级菜单的二级菜单数据数组// 找到当前一级中所有不重复的二级的pidlet pidarr = [...new Set(carr.map(itp => itp.pid))]// 根据当前一级的不重复的二级pid遍历生成当前一级的二级:pidarr.map(pid=>{// 每个二级对象let pobj = {}let parr = [] // 存一种二级的数组result.map(pitem=>{ // 找出result中cid等于一级id数组中每个元素的值if(pitem.pid===pid){parr.push(pitem)}})// 存当前二级下不重复的三级qpidlet qidarr = [...new Set(parr.map(pit => pit.qpid))]// 找出当前一级的数组中pid等于pidarr中的值的某项对象carr.map(pits=>{if(pits.pid === pid){pobj.pid = pits.pidpobj.projects_name = pits.projects_name// 处理三级数据:let qparr = []qidarr.map(qid=>{let qpobj = {}parr.map(qpit=>{if(qpit.qpid ===qid){qpobj.qpid = qpit.qpidqpobj.common_name = qpit.common_name}})qparr.push(qpobj)})pobj.qchild = qparr}})pchildtemp.push(pobj)})cobj.pchild = pchildtempdatalist.push(cobj)})// 打印结果:console.log(datalist)
打印数据如下图:
提示:本文图片等素材来源于网络,若有侵权,请发邮件至邮箱:810665436@qq.com联系笔者删除。
笔者:苦海