关于element-ui 中的级联菜单树形结构变化问题

树形结构转化为平铺

// 正向-树形结构转平铺
// 从外到内依次递归,有 children 则继续递归
function treeToArr(data, pid=null, res=[]) {
  data.forEach(item => {
    res.push({ pid: pid, id: item.id, name: item.name });
    if(item.children && item.children.length !== 0) {
      treeToArr(item.children, item.id, res);
    }
  });
  return res;
};

const arr = treeToArr(data);
console.log(arr);

平铺类型转换为树形结构

 1 // 依次在数组中找到每一层级对应的元素,同时每个元素的 children 属性对应的 value 通过 pid 去找到,然后递归执行下去
 2 function arrToTree(arr, pid=null) {
 3   const res = [];
 4   arr.forEach(item => {
 5     if(item.pid === pid) {
 6       // 这样每次都需要遍历整个数组,因此时间复杂度为 n*n
 7       // const children = arrToTree(arr, item.id)   
 8 
 9       // 往下递归时,每次数组的大小都在减小,每次都筛选掉父代元素,最终的时间复杂度为 n*logn
10       const children = arrToTree(arr.filter(v => v.pid !== pid), item.id);
11       if(children.length) {
12         res.push({ ...item, children })
13       }else {
14         res.push({ ...item })
15       }
16     }
17   });
18   return res;
19 };
20 
21 const tree = arrToTree(arr);
22 console.log(JSON.stringify(tree, null, 2));

 

posted @ 2021-12-03 14:14  王依一  阅读(240)  评论(0)    收藏  举报