我具有如下结构的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;
}
在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));