[英]multiply 2 value from each array of objects then add the multiplied numbers to get a total number in Reactjs/Javascript
I am building an eCommerce app where I want to get the total price of users ordered items.我正在构建一个电子商务应用程序,我想在其中获取用户订购商品的总价格。 I've an array called 'orders' where I have all the ordered items.我有一个名为“orders”的数组,其中包含所有订购的物品。 each items has 2 key calles payablePrice & purchasedQty.每件商品都有 2 个关键调用,payablePrice 和 purchaseQty。 I want to multiply this 2 keys then i want to add the multiplied number to get the total.我想将这两个键相乘,然后我想将相加的数字相加得到总数。 Plz let me know if theres a better way to get the total,请让我知道是否有更好的方法来获得总数,
Here is my array of objects:这是我的对象数组:
This is what i tried:这是我尝试过的:
{user.orders.map((order, i) => (
<tr key={i}>
<td> {order._id} </td>
<td> {userName} </td>
<td>
{order.items.map((item) => item.payablePrice * item.purchasedQty)}
</td>
<td>status</td>
</tr>
))}
which is not working.Plz help me get the total price of each order这是行不通的。请帮我获取每个订单的总价格
So, i just had to use.reduce after.map() in the correct way this code solved my problem所以,我只需要以正确的方式使用.reduce after.map() 这段代码解决了我的问题
{user.orders.map((order, i) => (
<tr key={i}>
<td> {order._id} </td>
<td> {userName} </td>
<td>
{order.items
.map((item) => item.payablePrice * item.purchasedQty)
.reduce((acc, current) => {
return acc + current;
}, 0)}
</td>
<td>status</td>
</tr>
))}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.