JS的有關遞歸的知識點(數據無限級聯的實現)


所用測試數據:

 1 const data = [
 2   {
 3     "area_id": 5,
 4     "name": "廣東省",
 5     "parent_id": 0,
 6   }, 
 7   {
 8     "area_id": 6,
 9     "name": "廣州市",
10     "parent_id": 5,
11   },
12   {
13     "area_id": 7,
14     "name": "深圳市",
15     "parent_id": 5,
16   },
17   {
18     "area_id": 9,
19     "name": "昌平區",
20     "parent_id": 4,
21   },
22   {
23     "area_id": 4,
24     "name": "北京市",
25     "parent_id": 3,
26   },
27   {
28     "area_id": 3,
29     "name": "北京",
30     "parent_id": 0,
31   },
32   {
33     "area_id": 2,
34     "name": "測試子地區",
35     "parent_id": 1,
36   },
37   {
38     "area_id": 1,
39     "name": "測試地區",
40     "parent_id": 0,
41   }
42 ]
View Code

遞歸實現無限級數據:

 1 function toTreeData(data,pid){
 2   function tree(id) {
 3     let arr = []
 4     data.filter(item => {
 5       return item.parent_id === id;
 6     }).forEach(item => {
 7       arr.push({
 8         area_id: item.area_id,
 9         label: item.name,
10         children: tree(item.area_id)
11       })
12     })
13     return arr.length>0?arr:""
14   }
15   return tree(pid) // 第一級節點的父id,是null或者0,視情況傳入
16 }
17 var tmp=toTreeData(data,0);
18 console.log(tmp);
View Code
對象的方式實現無限級數據維護
 1 function setTreeData(arr) {
 2   // 刪除所有 children,以防止多次調用
 3   arr.forEach(function (item) {
 4       delete item.children;
 5   });
 6   let map = {}; // 構建map
 7   arr.forEach(i => {
 8     map[i.area_id] = i; // 構建以area_id為鍵 當前數據為值
 9   });
10 
11   let treeData = [];
12   arr.forEach(child => {
13     const mapItem = map[child.parent_id]; // 判斷當前數據的parent_id是否存在map中
14 
15     if (mapItem) { // 存在則表示當前數據不是最頂層數據
16     
17       // 注意: 這里的map中的數據是引用了arr的它的指向還是arr,當mapItem改變時arr也會改變,踩坑點
18       (mapItem.children || ( mapItem.children = [] )).push(child); // 這里判斷mapItem中是否存在children, 存在則插入當前數據, 不存在則賦值children為[]然后再插入當前數據
19     } else { // 不存在則是組頂層數據
20       treeData.push(child);
21     }
22   });
23 
24   return treeData;
25 };
View Code

總結:遞歸其實遇到數據格式類似且嵌套的時候會使用到


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM