我有一个包含多个对象的数组,每个对象都有一个日期、数量和ID作为键。
我想按月对所有对象进行分组,然后返回每个月的金额键的总和。
这是我的第一个方法,但我很确定这不是正确的方法。
我手动定义每个月的开始和结束。
有没有其他更动态的方法?
1 -获取每个月的开始和结束日期
2 -按月对数组分组,不使用lodash(我愿意使用moment.js)
3 -对每个月的值求和
3 -返回月份名称+总计
json中的数组结构
"expenses": [
{
"amount": 5.97,
"date": "09/01/2022",
"id": 1
},
]
React中的逻辑
const MonthsTotal = ({ expenses }) => {
let novemberTotal = 0;
let decemberTotal = 0;
expenses
.filter((items) => {
return items.date >= "11/01/2022" && items.date <= "11/31/2022";
})
.forEach((item) => {
novemberTotal += item.amount;
});
expenses
.filter((items) => {
return items.date >= "12/01/2022" && items.date <= "12/31/2022";
})
.forEach((item) => {
decemberTotal += item.amount;
});
React中的输出
这就是我输出数据的方式
return (
<Box>
<Card variant="outlined">
<div> November </div>
<div>{novemberTotal}</div>
</Card>
</Box>
<Box>
<Card variant="outlined">
<div>December</div>
<div>{decemberTotal}</div>
</Card>
</Box>
)
export default MonthsTotal;
1条答案
按热度按时间toe950271#
我首先将费用按月份分组,然后合计它们的金额,在这个例子中我使用了lodash和date-fns,但是可以用任何其他库来替换它们。
接下来,您可以将所有月份传递给React组件,并对它们进行循环