Display the length of the product array when I have multiple JSON objects

I am working with the following JSON data:

{
    "StatusCode": 0,
    "StatusMessage": "OK",
    "StatusDescription": [
        {
            "_id": "12123",
            "dateCreated": "2019-12-03T13:45:30.418Z",
            "pharmacy_id": "011E752345553380ABC13FFA163ECD15"
            "products": [
                {
                    "productID": "1",
                    "quantity": 3,
                    "product_name": "BETADINE",
                    "price": 10
                },
                {
                    "productID": "2",
                    "quantity": 1,
                    "product_name": "EUCARBON",
                    "price": 10
                }
            ]
        },
        {
            "_id": "56233",
            "dateCreated": "2019-12-04T09:55:21.555Z",
            "pharmacy_id": "011E762345552280FBC13FFA163ECD10"
            "products": [
                {
                    "productID": "44",
                    "quantity": 1,
                    "product_name": "BETADINE",
                    "price": 10
                }
            ]
        }
    ]
}

My goal is to extract the total number of products in this JSON structure. For example, in this case, there are 2 pharmacies and a total of 5 products. I want to display this count in my shopping cart.

To achieve this, I'm using the following function to fetch the JSON data from an API:

public cart: Shop[];
  cartlength: number;

  ngOnInit(): void {
        this.shopservice.getShoppingCart().subscribe(
            cart => {
                this.cart = cart;
                this.cartlength = cart.length;
            },
            err => console.error('errorrrrrrr', err),
            () => console.log('error')
        );
    }

In my HTML file, I am displaying the product count using the following code snippet:

<ActionItem ios.systemIcon="9" ios.position="left" android.position="actionBar"  [text]='cartlength'></ActionItem> 

Any suggestions or ideas on how to improve this implementation?

Answer №1

If you have an array called "cart" that contains information about pharmacies, you can use the reduce method to calculate the total quantity of all products for each pharmacy.

this.cartlength = this.cart.reduce((count, pharmacy) => {
    count += pharmacy.products.reduce((totalQty, product) => {
        return totalQty += product.quantity;
    }, 0)
    return count;
}, 0)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Does this fall under the category of accepted practices for employing an effect in Angular?

I am working on integrating an Angular directive with a signal that receives values from a store selector. This signal is crucial for determining whether a button should be disabled or not. I'm curious about the best approach to listen to this signal ...

There was an issue with the JSON parsing process due to an unexpected token 'o' at position

Trying to extract titles from a JSON object for a specific feature, here's an example of the JSON structure: [ { "title": "Example 1", "url": "http:\/\/www.example1.com\/" }, { "title": "Example 2", "url": "http:& ...

Utilize a Python script to transmit data to JavaScript through JSON in order to dynamically alter the content of

Currently, I am developing an interactive display that utilizes sensors on a raspberry pi. The display is set to show a webpage and I have implemented a python script to handle sensor interaction. My goal is to change the displayed web page when a user p ...

Potential uncertainty in Angular FormControl email validation due to potential null Object

Whenever I run the command ng s --aot, I encounter this message: Object is possibly 'null'. I've been trying various solutions all morning to resolve it, but without success. The issue seems to be related to objects like email.valid, dirty, ...

Transforming form inputs into JSON structure

<form name = 'test' > <input type='text' name = 'login'> <input type='email' name = 'email'> </form> When I try to convert the form data using JSON.serialize($(form)).serial ...

The issue encountered during a POST request in Postman is a SyntaxError where a number is missing after the minus sign in a JSON object at position 1 (line 1

Running my API in a website application works flawlessly, but encountering SyntaxError when testing it in Postman - specifically "No number after minus sign in JSON at position 1" (line 1 column 2). The data is correctly inputted into the body of Postman a ...

Prevent side menu from automatically hiding when clicking on the heading

My menu is set up with headings and subheadings. When I click on the headings, it expands to display the corresponding subheadings, but it automatically collapses when clicking on the headings. I want it to stay expanded when clicking on the headings. He ...

Angular displays a datalist input as "[object Object]" once a value has been selected

In my form, I have the following section: <div formArrayName="studentPublishing" *ngFor="let all of getstudentPublishing().controls; index as i"> <div class="form-group data"> <input type="text& ...

Using Angular rxjs to efficiently make multiple API calls and merge their results in one response

After successfully making multiple calls to the same API with different payloads and merging the results into arrays of objects, I now need to mark each object in the result array for filtering purposes. For example, I want to add a property called api_id ...

The Axios GET method retrieves a response in the form of a string that represents an object

I have developed a function that triggers an axios Request. I am working with typescript and I am avoiding the use of any for defining return data types of both the function and the axios request itself. The issue arises when the returned object contains ...

The frontend is not triggering the Patch API call

I am having trouble with my http.patch request not being called to the backend. This issue only occurs when I try calling it from the frontend. Oddly enough, when I tested it in Postman, everything worked perfectly. Testing the backend on its own shows t ...

Using Struts 2 for dynamic web development with jQuery: utilizing sj:select and JSON

Currently, I am utilizing the struts 2 jquery plugin select component. The action looks like this: SampleAction { private List<SampleVO> samples; //With setters and getters private List<AnotherVO> anotherList; //With setters an ...

Searching for all integer values in a JSON formatted text file

I have a .txt file formatted like a JSON file, containing lists, dictionaries, integers, etc. I need to extract all the numbers from it and calculate their sum. {"e":[[{"e":86,"c":23,"a":{"a":[120,169,"green","red","orange"],"b":"red"},"g":"yellow","b": ...

The issue with Angular's Array.push method arises when only the last object in the array is being pushed after a mat-checkbox

I am currently working with two components called item-list and item. The item-list component is responsible for displaying a list of items with checkboxes. I have been facing an issue where the Array that stores the checked items only retains the last ite ...

Accessing data from a complex JSON structure

Hello all, I am currently attempting to extract the subject name value from a JSON file called dataArray that has already been processed through NSJSONSerialization: -0: { id: "55edc05848177ec741daf79e" firstName: "Brad" rating: 4.2 lessons: 5 text: "Les ...

What sets apart extending and intersecting interfaces in TypeScript?

If we have the following type defined: interface Shape { color: string; } Now, let's explore two different methods to add extra properties to this type: Using Extension interface Square extends Shape { sideLength: number; } Using Intersection ...

Unable to subscribe to mergeMap observable in Angular 13

I am currently working on implementing a connection scenario in Angular that is based on user roles. When the user clicks on the "CONNEXION" button after filling out the form with their username and password, two API URLs are triggered to facilitate the sa ...

organize and identify a JSON data using sorting and matching techniques

Having a JSON structure as shown below: [ { "id": "1", "freq": "1", "value": "Tiruchengode", "label": "Tiruchengode" }, { "id": "2", "freq": "1", "value": "Coimbatore", "label": " ...

Utilizing svgr in NextJS with TypeScript and Webpack

I have a collection of separate svg files that I want to load in React and use as React components. Here is an example of how I am trying to do this: import SampleIcon from '@/components/editor/icons/add-column-after.svg'; <SampleIcon classNam ...

Passing parent HTML attributes to child components in Angular 2

Is there a way to pass HTML attributes directly from parent to child without creating variables in the parent's .ts class first? In the sample code below, I am trying to pass the "type=number" attribute from the parent to the app-field-label component ...