前端获取后端的数组对象处理(去重,排序,转为树状结构)

这篇博客介绍了如何在前端处理来自后端接口的数组对象,包括使用元素ID进行去重,对数据进行排序,并将扁平数据转换成树状结构,以优化数据展示。

后端接口数据处理,对数组对象进行 去重(通过元素id去重),排序,转为树状结构

下面为后端转过来的一个扁平数据

var data = [
      {
        id: '1',
        staffName: '陈三三',
        trueProRank: { id: "11", description: "交警", codeIndex: 11, category: "警务人员", categoryIndex: 1 }
      },
      {
        id: '2',
        staffName: '张三三',
        trueProRank: { id: "22", description: "公安", codeIndex: 22, category: "警务人员", categoryIndex: 1 }
      },
      {
        id: '2',
        staffName: '李三三',
        trueProRank: { id: "33", description: "特警", codeIndex: 33, category: "警务人员", categoryIndex: 1 }
      },
      {
        id: '4',
        staffName: '王三三',
        trueProRank: { id: "33", description: "民警", codeIndex: 33, category: "警务人员", categoryIndex: 1 }
      },
      {
        id: '5',
        staffName: '赵三三',
        trueProRank: { id: "44", description: "出纳", codeIndex: 44, category: "财务人员", categoryIndex: 2 }
      },
      {
        id: '6',
        staffName: '陈三三',
        trueProRank: { id: "55", description: "税务", codeIndex: 55, category: "财务人员", categoryIndex: 2 }
      },
    ];
  }
// 对后端数据先进行去重
  toHeavy(arr: any[]) {
    const hash = [];
    for (const item of arr) {
      if (hash.indexOf(item) === -1) {
        hash.push(item);
      }
    }
    return hash;
  }
  // 根据不同职级id进行排序
  compare(id) {
    return (a, b) => {
      const value1 = a[id];
      const value2 = b[id];
      return value1 - value2;
    };
  }
  // 把后端接口数据转为树状结构
  treeArr(arr, key) {
    let result = [];
    const obj = {};
    for (const item of arr) {   // 对arr通过key去重处理,得到一个result
      if (!obj[item[key]]) {
        result.push(item);
        obj[item[key]] = true;
      }
    }
    result = result.map(item => {   // 给result拓展一个children属性
      item = { ...item, children: [] };
      return item;
    });
    result.map(a => {   // 获得result下children的数组集合
      arr.map(b => {
        if (a[key] === b[key]) {
          a.children.sort(this.compare('id'));    // children根据id排序
          a.children.push(b);
          return a;
        }
      });
    });
    result.sort(this.compare('id'));    // result根据id排序
    return result;
  }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值