JavaScript、TypeScript 实现通过某个属性值对「对象数组」进行

【JavaScript、TypeScript 实现通过某个属性值对「对象数组」进行】背景
Antd 表格批量处理获取数据相关逻辑
在实际项目业务逻辑开发中 , 前端调用接口请求数据,后台返回的列表数据格式一般是没按某一控制条件进行分组,这时候为了实现某些业务需求 , 就需要我们自己对数据重新进行处理 , 从而获得我们想要的数据结构 。
比如我想获得候选的内容中每个类别是多少数量
下面就是通过某个属性值对「对象数组」进行分组生成「结果对象数组」,一个分类的过程 。
效果
const list = [{id: 1,name: "杨一",position: "前端"},{id: 2,name: "杨二",position: "前端"},{id: 3,name: "杨三",position: "前端"},{id: 4,name: "杨四",position: "后端"},{id: 5,name: "杨五",position: "后端"}, {id: 6,name: "杨六",position: "算法"},{id: 7,name: "杨七",position: "算法"},{id: 8,name: "杨八",position: "算法"},]countSelectedMember(list)
变成
踩坑方法一
const countSelectedMember = (array: any[]): any[] => {const classifiedMember: any[] = [];for (let i = 0; i < array.length; i++) {if (array[i].position === null) continue;//注意脏数据else if (classifiedMember.length == 0) {classifiedMember.push({position: array[i].position,data: [array[i]],});} else {let index: number = classifiedMember.findIndex((item) => item.position == array[i].position,);if (index >= 0) {classifiedMember[index].data.push(array[i]);} else {classifiedMember.push({position: array[i].position,data: [array[i]],});}}}return classifiedMember;};
方法二
const countSelectedMember = (selectedMember: any[]): Map => {let mapPosition: Map = new Map();for (const member of selectedMember) {if (member.position === null) {if (mapPosition.has('职位类别缺失')) {const curNo: number = mapPosition.get('职位类别缺失');mapPosition.set('职位类别缺失', curNo + 1);} else {mapPosition.set('职位类别缺失', 1);}} else if (!mapPosition.has(member.position[0])) {mapPosition.set(member.position[0], 1);} else {const cur: any | undefined = mapPosition.get(member.position[0]);mapPosition.set(member.position[0], cur + 1);}}return mapPosition;};// 后续渲染let memberPosition: Map = countSelectedMember(selectedRows);let ul: any[] = [];memberPosition.forEach((value, key) =>ul.push(

  • {`${key}:${value}名`}
  • ));