扁平转树形、树形转扁平结构

复制代码
复制代码
复制代码
复制代码
复制代码

 

复制代码

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/**
 *
 * @param {Array} data
 * @param {string} pid 子树找父级的标识,这里面默认子树的标识为id,如果不为id,就再传一个子树id标识
 * @param {string} child 自定义子树字段名称
 * @returns
 */
export function makeTree(data,pid,child){
    let parents = data.filter(p => p[pid] === '0' ),
        children = data.filter(c => c[pid] !== '0');
    dataToTree(parents, children);
    return parents;
 
function dataToTree(parents, children){
  parents.map(p => {
    children.map((c, i) => {
      if(c[pid] === p.unionId){
        let _children = JSON.parse(JSON.stringify(children));
        _children.splice(i, 1);
        dataToTree([c], _children);
        if(p[child]){
          p[child].push(c);
        }else{
          p[child] = [c];
        }
      }
    })
  })
}
}
 
/**
 *
 * @param {Array} arrs 树形数据
 * @param {string} childs 树形数据子数据的属性名,常用'children'
 * @param {Array} attrArr 需要提取的公共属性数组(默认是除了childs的全部属性)
 * @returns
 */
 
 export function extractTree(arrs,childs,attrArr){
  let attrList = [];
  if(!Array.isArray(arrs)&&!arrs.length)return [];
  if(typeof childs !== 'string')return [];
  if(!Array.isArray(attrArr)||Array.isArray(attrArr)&&!attrArr.length){
    attrList = Object.keys(arrs[0]);
    attrList.splice(attrList.indexOf(childs), 1);
  }else{
    attrList = attrArr;
  }
  let list = [];
  const getObj = (arr)=>{
    arr.forEach(function(row){
      let obj = {};
      attrList.forEach(item=>{
        obj[item] = row[item];
      });
      list.push(obj);
      if(row[childs]){
        getObj(row[childs]);
      }
    })
    return list;
  }
  return getObj(arrs);
}// 递归查找子集
 function transferArr2Tree(data, pid = 0) {
  const result = []
  data.forEach(item => {
    if (item.pid === pid) {
      item.chidlren = transferArr2Tree(data, item.id)
      result.push(item)
    }
  })
  return result
 }
 
function transferTree2Arr(arr) {
  let res = []
  for(const item of arr) {
    res.push(item)
    if (item.chidlren && !!item.chidlren.length) {
      res = res.concat(transferTree2Arr(item.chidlren))
    }
  }
  return res
}
 
// 数组的扁平化
function flatten(arr) {
  let result = []
  for (let i = 0; i < arr.length; i++) {
    if (Array.isArray(arr[i])) {
      result = result.concat(flatten(arr[i]))
    } else {
      result.push(arr[i])
    }
  }
  return result
}  
posted @   糖锡  阅读(60)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】
点击右上角即可分享
微信分享提示