gpt4 book ai didi

如果对象的其他值相同,则 JavaScript SUM 对象值

转载 作者:行者123 更新时间:2023-12-03 00:54:50 25 4
gpt4 key购买 nike

我对 JS 高数组方法很陌生,我有一个包含成本类别和值的对象数组,如下所示:

[{category: "Bars", amount: 31231},
{category: "Transport", amount: 1297},
{category: "Utilities", amount: 12300},
{category: "Bars", amount: 2000},
{category: "Transport", amount: 2500},
{category: "Education", amount: 21321}]

我的目标是减少这个数组并对“金额”值求和,如下所示:

[{category: "Bars", amount: 33231},  //31231+2000
{category: "Transport", amount: 3797}, //1297+2500
{category: "Utilities", amount: 12300},
{category: "Education", amount: 21321}]

我尝试了reduce()和forEach(),但我无法真正找到解决问题的方法。谢谢!

最佳答案

您应该使用reduce方法来执行此操作,因此您将使用项目迭代数组,并且对于每个项目,您将询问该类别是否不存在于 newObject 中。然后用0值初始化,然后求和。

var objects = [{category: "Bars", amount: 31231},
{category: "Transport", amount: 1297},
{category: "Utilities", amount: 12300},
{category: "Bars", amount: 2000},
{category: "Transport", amount: 2500},
{category: "Education", amount: 21321}];

var newObjectsMerged = objects.reduce((object, item) => {
var category = item.category;
var amount = item.amount;
if (!object.hasOwnProperty(category)) {
object[category] = 0;
}

object[category] += amount;
return object;
}, {});

console.log("newObjectsMerged", newObjectsMerged);

关于如果对象的其他值相同,则 JavaScript SUM 对象值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52882345/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com