【问题标题】:Cumulative quantity of type X products in javascriptjavascript中类型X产品的累积数量
【发布时间】:2020-06-03 13:00:06
【问题描述】:

情况就是这样:每个订单可以包含多种类型,数量不同。对于每个订单项目,我想要每种类型的总数量。

[{
  "order" : 1,
  "orderDetails" : [{
    "quantity" : 10,
    "product" : {
      "productType" : "A"
    },
    "quantity" : 20,
    "product" : {
      "productType" : "A"
    },
    "quantity" : 10,
    "product" : {
      "productType" : "B"
    }
  }]
}]

这是我的代码,它可以完成这项工作,但我正试图让它变得更加优雅,不知何故。我很确定那里有冗余代码,我不确定我是否正确使用了 reduce

    const orders = data.map(h => {
    const newArray = [];
    h.orderDetails_ = h.orderDetails.reduce(function(a, b, i) {
        if (newArray[b.product.productType] == undefined) {
          newArray[b.product.productType] = b.quantity;
          return newArray;  
        } else {
          newArray[b.product.productType] += b.quantity;
          return newArray;
        }
      }, 0);
      return h;
    });

【问题讨论】:

    标签: arrays dictionary ecmascript-6 reduce


    【解决方案1】:

    好吧,对于任何人来说,这是更好和正确的版本

        const orders = data.map(h => {
          h.orderDetails_ = h.orderDetails.reduce((orderTotals, order) => {
            orderTotals[order.product.productType] =
              (orderTotals[order.product.productType] || 0) + order.quantity;
            return orderTotals;
          }, {});
          return h;
        });
    

    【讨论】:

      猜你喜欢
      • 2019-03-30
      • 1970-01-01
      • 2017-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-21
      • 2020-11-21
      相关资源
      最近更新 更多