Javascript 如何在React中使用reduce获得嵌套数组中的累积价格
在我的mapStateToProps中,我有一个对象(产品)数组。在每个对象中,都有一个“addon”数组,这是另一个对象数组。如何计算每个产品的所有“插件”的价格Javascript 如何在React中使用reduce获得嵌套数组中的累积价格,javascript,reactjs,redux,reduce,Javascript,Reactjs,Redux,Reduce,在我的mapStateToProps中,我有一个对象(产品)数组。在每个对象中,都有一个“addon”数组,这是另一个对象数组。如何计算每个产品的所有“插件”的价格 const mapStateToProps = (state) => { return ({ ...state, totalItemsAddonPrice: ????, totalItemPrice: state.toggleCartReducer.cartItems.reduce((accum
const mapStateToProps = (state) => {
return ({
...state,
totalItemsAddonPrice: ????,
totalItemPrice: state.toggleCartReducer.cartItems.reduce((accumulatedQuantity, cartItem) => accumulatedQuantity + cartItem.quantity * cartItem.price, 0),
itemCount: state.toggleCartReducer.cartItems.reduce((accumulatedQuantity, cartItem) => accumulatedQuantity + cartItem.quantity, 0),
tax: state.toggleCartReducer.cartItems.reduce((accumulatedQuantity, cartItem) => accumulatedQuantity + cartItem.quantity * cartItem.price, 0) * .0725
})}
目标是得到总价格
谢谢您需要像这样使用嵌套的reduce来查找addon total
const exampleData=[
{
名称:“产品1”,
价格:10,,
插件:[
{
加载项名称:“第一个加载项”,
附加价格:3
},
{
加载项名称:“第二个加载项”,
附加价格:1
},
]
},
{
名称:“产品2”,
价格:15,,
插件:[
{
加载项名称:“product2加载项”,
附加价格:3
},
{
加载项名称:“product2第二个加载项”,
附加价格:2
},
]
}
]
const addOntotal=exampleData.reduce((总价,项目)=>
totalPrice+item.addons.reduce((total,addon)=>total+addon.addonPrice,0),0);
log(addOntotal)
您可以使用所有价格创建一个数组,然后使用
exampleData
.flatMap(item=>[item.price,…item.addons.map(a=>a.addonPrice)])
.减少((总计,价格)=>总计+价格,0)
计算附加组件总价格有多种方法
如果您对for
循环感到满意,可以在此处使用
let price=0;
for(exampleData的常量乘积){
for(product.addons的常量加载项){
价格+=加载项。加载项价格
}
}
上面的代码将遍历exampleData。exampleData的每个元素都由变量product
保存<代码>产品是一个带有插件
数组的对象。将对象中的addonPrice
添加到price会得到所需的结果
但是,如果您习惯于使用,代码会更短,但可能需要一些时间才能理解它
const price=exampleData.reduce(
(prodAcc,prod)=>{
return prodAcc+prod.addons.reduce(
(addonAcc,curAddon)=>{
返回addonAcc+curAddon.addonPrice
}, 0
)
}, 0
)
exampleData = [
{
name:"product1",
price:10,
addons: [
{
addonName: "first add on",
addonPrice: 3
},
{
addonName: "second add on",
addonPrice: 1
},
]
},
{
name:"product2",
price:15,
addons: [
{
addonName: "product2 add on",
addonPrice: 3
},
{
addonName: "product2 second add on",
addonPrice: 2
},
]
}
]
totalItemsAddonPrice = exampleData.reduce((accum, curr) => {
return accum + curr.addons.reduce((acc, cur) => {
return acc + cur.addonPrice
}, 0)
}, 0)