首页 >> 大全

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

2023-12-21 大全 27 作者:考证青年

背景

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<string, number> => {let mapPosition: Map<string, number> = 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<string, number> = countSelectedMember(selectedRows);let ul: any[] = [];memberPosition.forEach((value, key) =>ul.push(<li>{`${key}:${value}`}</li>));

关于我们

最火推荐

小编推荐

联系我们


版权声明:本站内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 88@qq.com 举报,一经查实,本站将立刻删除。备案号:桂ICP备2021009421号
Powered By Z-BlogPHP.
复制成功
微信号:
我知道了