【发布时间】:2020-01-25 06:31:28
【问题描述】:
我的 js 对象数组的结构如下所示,
items= [
{
discount: 27.6,
name: 'Floy Vandervort',
price: 230,
quantity: 3,
taxable: 662.4
},
{
discount: 122.88,
name: 'Adriel Abshire II',
price: 256,
quantity: 6,
taxable: 1413.12
},
{
discount: 159.66,
name: 'Tabitha Stroman',
price: 887,
quantity: 2,
taxable: 1614.34
},
{
discount: 27.6,
name: 'Floy Vandervort',
price: 230,
quantity: 3,
taxable: 662.4
},
{
discount: 122.88,
name: 'Adriel Abshire II',
price: 256,
quantity: 6,
taxable: 1413.12
},
{
discount: 159.66,
name: 'Tabitha Stroman',
price: 887,
quantity: 2,
taxable: 1614.34
},
{
discount: 27.6,
name: 'Floy Vandervort',
price: 230,
quantity: 3,
taxable: 662.4
},
{
discount: 122.88,
name: 'Adriel Abshire II',
price: 256,
quantity: 6,
taxable: 1413.12
},
{
discount: 159.66,
name: 'Tabitha Stroman',
price: 887,
quantity: 2,
taxable: 1614.34
}
]
我想避免基于name 属性的对象重复。所以我决定通过保留其评估来合并它们,如下所示,
用例
考虑属性name,在上面的数组中 Floy Vandervort 重复 3 次。要将其转换为单个对象,请通过添加保留值将它们合并为单个对象。因此,discount、quantity 和 taxable 属性应通过加法合并,但 price 属性除外。
我正在寻找一个最佳解决方案,我通过迭代原始数组并将合并的对象推送到另一个数组来实现。我想消除复杂性,有可能吗?如果是,如何?这是我正在使用的功能
function(items) {
let filtered = [];
items.forEach((item) => {
if (!isContains(filtered, item)) {
filtered.push(item);
} else {
index = filtered.findIndex((x) => x.name === item.name);
filtered[index].discount += item.discount;
filtered[index].quantity += item.quantity;
filtered[index].taxable += item.taxable;
}
});
return filtered;
}
function isContains(items, ob) {
items.forEach((item) => {
if (item.name === ob.name) {
return true;
}
});
return false;
}
【问题讨论】:
-
@CertainPerformance 我刚刚进行了编辑并放置了我正在使用的代码。
-
@CertainPerformance 这就是我想要的,谢谢。
标签: javascript arrays optimization duplicates array-merge