Home > Software engineering >  How to get accumulated price in a nested array using reduce in React.js
How to get accumulated price in a nested array using reduce in React.js

Time:11-16

I have an array of objects (cart products). In each object, there is an array of "ShopCartList", and productCartList another array of objects. How can I accumulate the price of all "Price" for each product? The cart API enter image description here

The goal is to get the total price and also total price when adding products from a different shop.

{
  "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"
        }
      ]
    }
  ]
}

it shows an error of undefined.

enter image description here

CodePudding user response:

This is how you can reduce to get the sum of a certain key from an array of objects.

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

The above code returns the total sum of prices of products from a single productCartList array. If you have multiple items inside your ShopCartList array and want to get the sum of all the prices from all the ProductCartLists, you can use reduce on the ShopCartList array like so

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

The above code get adds the sum of all the prices from all the different product carts.

Let me know if this helps!

  • Related