gpt4 book ai didi

javascript - 对值求和,并将具有相同 id 的对象值合并到一个新数组中

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

我有一个从服务器收到的项目对象。每个商品及其数量都必须由卖家保存,但是,在屏幕上显示时,我需要在新数组中独立于卖家对值进行总计。

[
{ code: 1, item: 'ball', salesman: 'Braan', quantity: 5, price: 10.00},
{ code: 1, item: 'shoe', salesman: 'Alex', quantity: 5, price: 20.00},
{ code: 1, item: 'ball', salesman: 'Max', quantity: 3, price: 10.00},
{ code: 1, item: 'shirt', salesman: 'Braan', quantity: 5, price: 15.00}
]

期望的输出是:

[
{ code: 1, item: 'ball', quantity: 8, price: 20.00},
{ code: 1, item: 'shoe', quantity: 5, price: 20.00},
{ code: 1, item: 'shirt', quantity: 5, price: 15.00}
]

最佳答案

基本上,您可以重新映射对象以删除 salesman 键。

const serverData = [{
code: 1,
item: 'ball',
salesman: 'Braan',
quantity: 5,
price: 10.00
},
{
code: 1,
item: 'shoe',
salesman: 'Alex',
quantity: 5,
price: 20.00
},
{
code: 1,
item: 'ball',
salesman: 'Max',
quantity: 3,
price: 10.00
},
{
code: 1,
item: 'shirt',
salesman: 'Braan',
quantity: 5,
price: 15.00
}
]

const result = serverData
.map((item, i, array) => {
const defaultValue = {
code: item.code,
item: item.item,
quantity: 0,
price: 0
}
const finalValue = array
.filter(other => other.item === item.item) //we filter the same items
.reduce((accum, currentVal) => { //we reduce them into a single entry
accum.quantity += currentVal.quantity;
accum.price += currentVal.price;
return accum;
}, defaultValue);

return finalValue;
})
.filter((item, thisIndex, array) => { //now our new array has duplicates, lets remove them
const index = array.findIndex((otherItem, otherIndex) => otherItem.item === item.item && otherIndex !== thisIndex && otherIndex > thisIndex);

return index === -1
})

console.log(result)

关于javascript - 对值求和,并将具有相同 id 的对象值合并到一个新数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54217863/

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