背景
Antd 表格批量处理获取数据相关逻辑
在实际项目业务逻辑开发中,前端调用接口请求数据,后台返回的列表数据格式一般是没按某一控制条件进行分组,这时候为了实现某些业务需求,就需要我们自己对数据重新进行处理,从而获得我们想要的数据结构。
比如我想获得候选的内容中每个类别是多少数量
下面就是通过某个属性值对「对象数组」进行分组生成「结果对象数组」,一个分类的过程。
- 此外,本人之前没接触过 TypeScript 因此 TS 代码写的比较丑陋、写成anyscript,弄懂逻辑就行
效果
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>));