【问题标题】:Get sum of price multiplied by quantity over nested arrays通过嵌套数组获取价格总和乘以数量
【发布时间】:2020-07-03 20:40:53
【问题描述】:

我有一个对象数组,在对象中有这样的数组

[ 
     {
       orderId: 123, orderStatus: 'Pending', date: 'june 13, 2020', 
       products: [ {product: 'choco', price: 300, qty: 3}, {product: 'milk', price: 350, qty: 2} ] 
     },
     {
       orderId: 124, orderStatus: 'Pending', date: 'june 13, 2020', 
       products: [ {product: 'butter', price: 100, qty: 1}, {product: 'milk', price: 350, qty: 2} ] 
     } 
]

我想总结产品的所有价格和数量(结果应该是 2400)。有没有办法做到这一点?我正在使用 React js 和 firestore 作为数据库。

【问题讨论】:

    标签: javascript arrays reactjs object sum


    【解决方案1】:

    你也可以使用map、reduce、flat函数,如下所示:

    const data = [ 
         {
           orderId: 123, orderStatus: 'Pending', date: 'june 13, 2020', 
           products: [ {product: 'choco', price: 300, qty: 3}, {product: 'milk', price: 350, qty: 2} ] 
         },
         {
           orderId: 124, orderStatus: 'Pending', date: 'june 13, 2020', 
           products: [ {product: 'butter', price: 100, qty: 1}, {product: 'milk', price: 350, qty: 2} ] 
         } 
    ]
    
    const pricesArray = data.map(item=>item.products.map(product=>product.price*product.qty));
    console.log(pricesArray.flat().reduce((acc,sum)=>acc+sum));

    标题

    【讨论】:

      【解决方案2】:

      const data = [{orderId: 123, orderStatus: 'Pending', date: 'june 13, 2020',products: [{ product: 'choco', price: 300, qty: 3 }, { product: 'milk', price: 350, qty: 2 }]},{orderId: 124, orderStatus: 'Pending', date: 'june 13, 2020',products: [{ product: 'butter', price: 100, qty: 1 }, { product: 'milk', price: 350, qty: 2 }]}]
      
      let sum = 0;
      
      for (let i = 0; i < data.length; i++) {
          for (let j = 0; j < data[i].products.length; j++) {
              sum += data[i].products[j].price * data[i].products[j].qty
          }
      }
      
      console.log(sum);

      【讨论】:

        猜你喜欢
        • 2023-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-08
        • 1970-01-01
        • 2023-01-14
        • 2021-07-21
        • 1970-01-01
        相关资源
        最近更新 更多