gpt4 book ai didi

javascript - 对对象数组中的两个值求和,然后插入到另一个对象数组中

转载 作者:行者123 更新时间:2023-11-30 20:07:21 24 4
gpt4 key购买 nike

我有一个名为商店的对象数组:

stores = [
{
storeId: 1,
city: "San Francisco",
state: "CA",
},
{
storeId: 2,
city: "Seattle",
state: "WA",
},
{
storeId: 3,
city: "Vancouver",
state: "BC",
},
{
storeId: 4,
city: "Los Angeles",
state: "CA",
},
]

和另一个称为项目的对象数组:

items = [
{
itemId: 1,
cost: 10,
price: 20,
sold: false,
_storeId: 1,
},
{
itemId: 2,
cost: 10,
price: 20,
sold: false,
_storeId: 1,
},
{
itemId: 3,
cost: 5,
price: 12,
sold: true,
_storeId: 2,
},
{
itemId: 4,
cost: 12,
price: 20,
sold: false,
_storeId: 3,
},
{
itemId: 5,
cost: 2,
price: 10,
sold: false,
_storeId: 4,
},
{
itemId: 6,
cost: 10,
price: 50,
sold: true,
_storeId: 4,
},
]

我想按商店汇总以下类别:

  • 总成本
  • 总价

然后按商店统计商品总数:

  • 总计

然后统计商店销售的商品小计:

  • 已售商品

所以我最终的存储数组看起来像这样:

storesUpdated = [
{
storeId: 1,
city: "San Francisco",
state: "CA",
totalCost: 20,
totalPrice: 40,
countTotalItems: 2,
countSoldItems: 0
},
{
storeId: 2,
city: "Seattle",
state: "WA",
totalCost: 5,
totalPrice: 12,
countTotalItems: 1,
countSoldItems: 1
},
{
storeId: 3,
city: "Vancouver",
state: "BC",
totalCost: 12,
totalPrice: 20,
countTotalItems: 1,
countSoldItems: 0
},
{
storeId: 4,
city: "Los Angeles",
state: "CA",
totalCost: 12,
totalPrice: 60,
countTotalItems: 2,
countSoldItems: 1
},
]

我试过映射 stores 数组但卡在了这里:

const storesUpdated = stores.map((store) => {
= {}
items.forEach(item => {
if (item._storeId === store.storeId) {
return totalCost {
'storeId' : item.storeId,

}
}
})
})

有什么想法吗?非常感谢。

最佳答案

const stores = [{storeId:1,city:"San Francisco",state:"CA",},{storeId:2,city:"Seattle",state:"WA",},{storeId:3,city:"Vancouver",state:"BC",},{storeId:4,city:"Los Angeles",state:"CA",},]
const items = [{itemId:1,cost:10,price:20,sold:!1,_storeId:1,},{itemId:2,cost:10,price:20,sold:!1,_storeId:1,},{itemId:3,cost:5,price:12,sold:!0,_storeId:2,},{itemId:4,cost:12,price:20,sold:!1,_storeId:3,},{itemId:5,cost:2,price:10,sold:!1,_storeId:4,},{itemId:6,cost:10,price:50,sold:!0,_storeId:4,},]

const storesUpdated = stores.map((store) => {
const updatedStore = { ...store,
totalCost: 0,
totalPrice: 0,
countTotalItems: 0,
countSoldItems: 0
}

items.forEach(item => {
if (item._storeId === store.storeId) {
updatedStore.totalCost += item.cost
updatedStore.totalPrice += item.price
updatedStore.countTotalItems += 1
updatedStore.countSoldItems += item.sold ? 1 : 0
}
})

return updatedStore
})

console.log(storesUpdated)

关于javascript - 对对象数组中的两个值求和,然后插入到另一个对象数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52769684/

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