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

后端接口数据处理,对数组对象进行 去重(通过元素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;
  }

你可能感兴趣的:(前端获取后端的数组对象处理(去重,排序,转为树状结构))