🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
~~~ <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script> </head> <body> <script> function Ajax(collback){ $.ajax({ type:"get", url:"./abc.json", dataType:"json", success:function(res){ collback(res) } }) } Ajax(res => { let arr = res; // arr为要处理的数组 a为数组中code的长度 (code的长度必须有规律) function aa(arr, a) { let arrlist = [] if (a > 9) { return arrlist } else { arr.forEach(ele => { if (ele.code.length == a ) { let item = {} item.name = ele.name; item.code = ele.code; let readylist=aa(arr,a+3); item.children=changechild(item.code,readylist) arrlist.push(item) } }); return arrlist } } //过滤子数组 e为上一级的code arr为要过滤的数组 function changechild(e,arr){ let news=[] for (let i = 0; i < arr.length; i++) if(arr[i].code.startsWith(e)){ news.push(arr[i]) } return news } let a = aa(arr, 3) console.log(a) }) //递归:首先递归一定会有迭代条件,当不满足情况直接return。满足条件然后进行数据处理(在数据处理的时候调用自身),把最总的结果return出去 </script> </body> </html> ~~~