【问题标题】:How to get accumulated price in a nested array using reduce in React.js如何在 React.js 中使用 reduce 获取嵌套数组中的累计价格
【发布时间】:2021-12-26 18:26:36
【问题描述】:

我有一组对象(购物车产品)。在每个对象中,有一个“ShopCartList”数组,productCartList 是另一个对象数组。如何累积每个产品的所有“价格”的价格?购物车 API

目标是在添加来自不同商店的产品时获得总价和总价。

{
  "CartID": "610a20c7d51ba524b7f949cd",
  "ShopCartList": [
    {
      "ShopID": "610a29e1d51ba524b7f949d0",
      "productCartList": [
        {
          "ProductID": "610a33f7d51ba524b7f949df",
          "VariationSKU": "062101403N",
          "Price": 2385.96,
          "Count": 1,
          "Attribute": {
            "Weight": "8.29",
            "Diameter": "5.40"
          },
          "CreatedDate": "2021-11-15T06:43:36.482Z",
          "CreatedBy": "610a20c7d51ba524b7f949cd",
          "LastUpdatedDate": "2021-11-15T06:43:36.482Z",
          "LastUpdatedBy": "610a20c7d51ba524b7f949cd"
        }
      ]
    }
  ]
}

它显示一个未定义的错误。

【问题讨论】:

  • 如果你可以发送 JSON 格式的文本,那么人们可以使用代码,这减少了你想在 javascript 中做吗?还是在 MongoDB 内部?
  • 想在 javascript 中执行此代码。

标签: javascript arrays reactjs json


【解决方案1】:

这是您可以通过归约从对象数组中获取某个键的总和的方法。

ProductCartList.reduce((a,b) => {
  return a + b["Price"]
},0);

以上代码从单个productCartList 数组返回产品价格的总和。如果您的ShopCartList 数组中有多个项目并且想要从所有ProductCartLists 中获取所有价格的总和,您可以像这样在ShopCartList 数组上使用reduce

ShopCartList.reduce((a,b) => {
  return a + b["ProductCartList"].reduce((a,b) => return a + b["Price"]);
},0);

上面的代码将所有不同产品购物车的所有价格相加。

如果这有帮助,请告诉我!

【讨论】:

  • 我收到错误 od undefined "reduce" 。
  • 出现未定义错误是因为data.ShopCartList 对象未定义。你能分享console.log(data)的输出吗?
  • 感谢您的帮助,我已经解决了错误。解决方案是我添加为 total = data.data.ShopCartList.reduce( (a, b) => a + b.productCartList.reduce((c, d) => c + d.Price * d.Count, 0), 0);
猜你喜欢
  • 2020-05-20
  • 1970-01-01
  • 2020-05-14
  • 1970-01-01
  • 1970-01-01
  • 2023-01-18
  • 2016-12-02
  • 2016-02-24
  • 1970-01-01
相关资源
最近更新 更多