减少对象数组以获得所需结果的最佳方法是什么?
const arr = [
{
"id": "561",
"count": "1",
"month": 7
},
{
"id": "561",
"count": "1",
"month": 7
},
{
"id": "561",
"count": "-1",
"month": 8
},
{
"id": "561",
"count": "1",
"month": 9
},
{
"id": "561",
"count": "-1",
"month": 9
}
]正如您所看到的,id匹配和一些月份匹配。我想实现的目标大致如下:
[
{
"id": "561",
"count": 2
"month": 7
},
{
"id": "561",
"count": -1,
"month": 8
},
{
"id": "561",
"count": 0,
"month": 9
}
]我基本上是在尝试获取每个id按月计算的总数。
发布于 2021-03-25 19:06:18
您可以使用Array.prototype.reduce根据id和月份对数组进行分组和评估
const arr = [
{
"id": "561",
"count": "1",
"month": 7
},
{
"id": "561",
"count": "1",
"month": 7
},
{
"id": "561",
"count": "-1",
"month": 8
},
{
"id": "561",
"count": "1",
"month": 9
},
{
"id": "561",
"count": "-1",
"month": 9
}
];
const res = Object.values(arr.reduce((acc, item) => {
if (acc[`${item.id}-${item.month}`]) {
acc[`${item.id}-${item.month}`] = {
...acc[`${item.id}-${item.month}`],
count: `${parseInt(acc[`${item.id}-${item.month}`].count) + parseInt(item.count)}`
}
} else {
acc[`${item.id}-${item.month}`] = item;
}
return acc;
}, {}));
console.log(res);
发布于 2021-03-25 19:07:11
下面是一个使用Array.prototype.reduce创建新数组并使用Array.prototype.find检查当前值是否已存在于新数组中的示例
const arr = [
{
"id": "561",
"count": "1",
"month": 7
},
{
"id": "561",
"count": "1",
"month": 7
},
{
"id": "561",
"count": "-1",
"month": 8
},
{
"id": "561",
"count": "1",
"month": 9
},
{
"id": "561",
"count": "-1",
"month": 9
}
]
const result = arr.reduce((acc, value) => {
const index = acc.findIndex(({id, month}) => id === value.id && month === value.month);
if( index > -1 ) {
acc[index]['count'] += Number(value.count);
}
else {
acc.push({...value, count: Number(value.count)});
}
return acc;
}, [])
console.log(result)
https://stackoverflow.com/questions/66798079
复制相似问题