使用递归进行处理树形数据
实现方式:
<script> //原始从服务器返回的数据 const temp = [ {"id":7, "parent":0, "name":"test0"}, {"id":8, "parent":0, "name":"test1"}, {"id":9, "parent":0, "name":"test2"}, {"id":68, "parent":0, "name":"test3"}, {"id":349, "parent":0, "name":"test4"}, {"id":74, "parent":7, "name":"test5"}, {"id":20, "parent":8, "name":"test6"}, {"id":21, "parent":8, "name":"test7"}, {"id":67, "parent":8, "name":"test8"}, {"id":185, "parent":9, "name":"test9"}, {"id":186, "parent":68, "name":"test10"}, {"id":187, "parent":68, "name":"test11"}, {"id":188, "parent":68, "name":"test12"}, {"id":189, "parent":68, "name":"test13"}, {"id":190, "parent":185, "name":"test14"}, {"id":191, "parent":185, "name":"test15"}, {"id":192, "parent":185, "name":"test16"}, {"id":350, "parent":349, "name":"test17"}, {"id":351, "parent":349, "name":"test18"}, ]; //处理好的数据 let res = getTree(temp,0,[]); console.log(res);//打印观察 //处理数据方法 function getTree(list,pid,data){ //获取所有一级 for(let item of list){ if(item.parent == pid){ data.push(item); } } //获取子级 for(let i of data){ i.children = []; getTree(list,i.id,i.children);//递归调用 if(i.children.length == 0){ delete i.children; } } return data; } </script>