如何在 Nodejs 中的 Mongoose Framework 中获取一段时间内的数据总和



我每天都有这样的数据输入

[
{
"food" : "1",
"price" : 1000,
"date" : "1 June"
},
{
"food" : "2",
"price" : 2000,
"date" : "2 June"
},
{
"drink" : "2",
"price" : 4000,
"date" : "1 July"
},
{
"drink" : "1",
"price" : 2000,
"date" : "2 July"
}
]

如何获得每个价格的总和? 每天输入数据的地方。 我想根据输入数据的月份获得总数。

也许它应该看起来像这样

[
{
"month" : "June",
"totalPrice" : 3000
},
{
"month" : "July",
"totalPrice" : 6000
}
]

请指导我这样做

此函数执行您需要的操作:

function getTotalPriceByMonth(data) {
const temp = {};
// You can use for..of, if you want
data.forEach(({ price, date }) => {
const [day, month] = date.split(' ');
if (month in temp) {
temp[month].totalPrice += price; 
} else {
temp[month] = { month, totalPrice: price };
}
});
return Object.values(temp);
}

因此,该函数将返回:

[
{ month: 'June', totalPrice: 3000 },
{ month: 'July', totalPrice: 6000 }
]

最新更新