转化前 const list = [ {id:1}, {pid:1,id:2}, {id:3}, {pid:3,id:4}, {pid:4,id:5} ] 转化后 [{ id:1, children:[{ pid:1, id:2 }] }, { id:3, children:[{ pid:3, id:4, children:[{ pid:4, id:5 }] }] }] getChildren(arr, id) { const res = [];//根据数据⼀致性,定义返回的结果 if (!id) { //如果没有传⼊id代表查找第⼀层数据 res.push(...arr.filter((item) => !item.pid)); } else {//传⼊id时,代表查找⼦节点 res.push(...arr.filter((item) => item.pid === id)); } res.forEach((item) => {//查找后要递归每个节点,从⽽实现children属性 const children = getChildren(arr, item.id) if (children.length) {//如果查找不到就不⽤赋值了,否则会多⼀个空数组 item.children = children; } }); return res; } //调⽤执⾏,list是转换前的数组,返回值是转换后的数组 getChildren(list)
标签:转换成,arr,封装,res,pid,children,item,树形,id From: https://www.cnblogs.com/Daguaishou0704/p/17308606.html