简体   繁体   中英

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. each items has 2 key calles payablePrice & purchasedQty. 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

The result i'm getting: 在此处输入图像描述

So, i just had to use.reduce after.map() in the correct way this code solved my problem

 {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>
      ))}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM