javascript - 在javascript中对具有相同ID的不同键的值求和
问题描述
我想知道如何在 javascript 中为相同 id 的相同 id 对象的多个键值求和,如何求和price
,total
在我的 obj 中我尝试了下面的代码
var obj = [{
id: "1",
price: 100,
total: 200
}, {
id: "1",
price: 100,
total: 200
}, {
id: "2",
price: 10,
total: 200
}]
let newobj = obj.reduce((a, c) => {
let filtered = a.filter(el => el.id === c.id);
if (filtered.length > 0) {
a[a.indexOf(filtered[0])].price += +c.price;
} else {
a.push(c);
}
return a;
}, []);
console.log(newobj);
预期输出:
result=[{
id: "1",
price: 200,
total: 400
},{
id: "2",
price: 10,
total: 200
}]
解决方案
代替Array#filter
,您可以Array#find
直接使用并获取该对象,而无需稍后查找索引。
如果找到只需添加想要的属性price
和total
.
如果您不想改变原始数据,您可以获取对象的副本以进行推送。
a.push({ ...c });
var array = [{ id: "1", price: 100, total: 200 }, { id: "1", price: 100, total: 200 }, { id: "2", price: 10, total: 200 }],
result = array.reduce((a, c) => {
let found = a.find(el => el.id === c.id);
if (found) {
found.price += c.price;
found.total += c.total;
} else {
a.push(c);
}
return a;
}, []);
console.log(result);
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}
推荐阅读
- java - 表达式语言无法访问 getter 方法
- java - 将 @Transactional 添加到测试中以避免 org.hibernate.LazyInitializationException no Session 错误。为什么需要它?
- .net - 我可以从 .NET 5 项目中添加对 .NET Framework DLL 的引用吗?
- java - 通过 Java 在 Mac OS 上停止正在运行的应用程序
- javascript - yahtzee 的threeofakind 和fourofakind 函数
- html - 如何使用beautifulsoup从html标签中提取所有标签
- mysql - 这个从 PostgreSQL 翻译到 MariaDB 的查询有什么问题?
- c# - 使用单个变量循环多个条件检查
- php - 一般错误:1364 字段“制造商名称”没有默认值
- pyspark - 如何在 pyspark 数据框中按 ID 将空值替换为另一行中的值?