大家一开始看到这个标题可能有点懵,咱先看一个需求,下面是模拟的数据。
const data = [
{ id: "001", type: "big", count: 10 },
{ id: "002", type: "small", count: 10 },
{ id: "003", type: "middle", count: 10 },
{ id: "004", type: "big", count: 10 },
{ id: "005", type: "small", count: 10 },
{ id: "006", type: "big", count: 10 },
{ id: "007", type: "small", count: 10 },
{ id: "008", type: "big", count: 10 },
{ id: "009", type: "middle", count: 10 },
{ id: "010", type: "big", count: 10 },
{ id: "011", type: "big", count: 10 },
{ id: "012", type: "small", count: 10 },
]
//将数据处理成这样
// 类型 数量
// small 40
// big 60
// middle 20
上面是后端返回的数据格式,今天有个小伙伴儿问我如何把这个数据处理成要求那样的,我这乍一看也没多难啊,首先第一步,应该把type值相同的挑选出来放在一起,我的代码是这样写的
let dataSort = []
data.forEach((obj) => {
let array = dataSort[obj['type']] || []
array.push(obj)
dataSort[obj['type']] = array
})
打印dataSort的结果是这样的:
我这一看,哎呀,正正好,再把相同类型的count加在一起,合并成一个不就完啦,然后我就开始陷入迷茫了,无论怎么处理都不合适,因为咱们得考虑后端如果除了这三种之外情况,所以不能直接按这三种情况直接读,但是这个【二维数组】我咋也遍历不出来了,看了半天我才注意到一个细节。
what?长度为零,我恍然大悟,这根本就不是一个二维数组,也不能那样去遍历,应该把他看作一个数组对象,去遍历对象的属性,然后我改进了一下我的代码
let dataSort = []
data.forEach((obj) => {
let array = dataSort[obj['type']] || []
array.push(obj)
dataSort[obj['type']] = array
})
console.log(dataSort)
let arr = Object.keys(dataSort)
const dataCombine=arr.map((item1) => {
const current={count:0}
dataSort[item1].map((item2) => {
current.type=item2.type;
current.count=current.count+item2.count;
})
return current
})
const clumns = [
{
title: '类型',
dataIndex: 'type',
key: 'name',
},
{
title: '总数',
dataIndex: 'count',
key: 'age',
},
]
return (
<Table
dataSource={dataCombine}
columns={clumns}
pagination={false}
/>
);
}
输出结果是这样的(请忽略样式,哈哈哈)
版权声明:本文为m0_58237008原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。