我的 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 次。要将其转换为单个对象,请通过加法保留值将它们合并为单个对象。因此,除了 price
属性外,discount
、quantity
和 taxable
属性应该通过加法合并。
我正在寻找一个最佳解决方案,我通过迭代原始数组并将合并的对象推送到另一个数组来实现。我想消除复杂性,可能吗?如果是,如何?这是我正在使用的功能
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;
}
最佳答案
在 forEach
回调中返回无效 - isContains
将始终返回 false。最好使用按名称索引的对象或 Map,以将计算复杂度降低一个数量级 - 然后您可以获取该对象的值以获取所需的数组:
const 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}];
function squish(items) {
const squishedItemsByName = items.reduce((a, { name, ...props }) => {
if (!a[name]) {
a[name] = { name };
}
Object.entries(props).forEach(([prop, val]) => {
a[name][prop] = (a[name][prop] || 0) + val;
});
return a;
}, {});
return Object.values(squishedItemsByName);
}
console.log(squish(items));
关于javascript - 合并对象使用 javascript 中的加法保留它的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58092055/