简体   繁体   English

从每个对象数组中乘以 2 个值,然后将相加的数字相加以获得 Reactjs/Javascript 中的总数

[英]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这是行不通的。请帮我获取每个订单的总价格

The result i'm getting:我得到的结果: 在此处输入图像描述

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.

相关问题 获取对象数组中每个用户的点赞总数 - JavaScript - Get total number of likes for each user in an array of objects - JavaScript 将数组值的总和乘以react组件中的输入值 - Add up total of array values multiplied by input value in react component 如何从 ReactJS 中的对象数组中获取值 - How to get a value from an array of objects in ReactJS 将数组中对象的所有值相加,但乘以数量 - Add up all values from objects in array but multiplied with quantity 如何将两个数字相加并将其与第三个数字相乘,并在 html 表单中以 javascript 的形式在禁用输入中显示总数? - How do I add two numbers and them multiply it with the 3rd number and show the total in a disabled input in a html form with javascript? javascript 乘以 2 显示总数和 gtotal 但只显示一个值? - javascript multiply 2 number show total and gtotal but show only one value? Javascript-从对象列表中获取最大数量,每个对象的属性均为数字 - Javascript - Get max number from list of objects, each with a property that is a number 获取JavaScript中相同对象的总数 - Get total number of same objects in javascript 从数组的总长度中减去并得到一个干净的数字[Javascript] - Subtract and get a clean number from the total length of the array [Javascript] 尝试将Number(value)相乘时给出NaN的数字数组 - Array of numbers giving NaN when trying to multiply Number(value)
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM