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

What is the process for generating an injected and a const object instance?

How can an instance of class A obtain a dependency on an instance of class O, while remaining a singleton for others? @injectable() class O{} // A must be single instance! @injectable() class A{ constructor(o: O){ console.log( 'is A inst ...

Increasing accessibility to floating point arrays in JSON data

Having some JSON data gathered via boost, I am struggling to figure out how to access certain elements within an array: Here is the JSON data: {"dvm_gnd": {"num" : 4, "value": [1,2,3,4]}, "xx_gn" : {"num : 1, "value": 5}} So far, I can easily extract the ...

Utilizing async await allows for the sequential processing of one item at a time within a For loop

Async await has me stumped, especially when it comes to processing items in an array with a 1 second delay: handleArrayProcessing() { clearTimeout(this.timer); this.timer = setTimeout(() => { for (const ...

Configuration error with MultiCapabilities

Encountering an issue while utilizing multiCapabilities with two web browsers (Firefox and Chrome). Below is a snippet from my configuration: exports.config = { allScriptsTimeout: 11000, seleniumAddress: 'http://localhost:4444/wd/hub', b ...

Activate the child for an update

Welcome! I am a newcomer to Angular and would greatly appreciate any assistance. The parent component of my picker has the ability to create various rules for each option. However, these rules are dynamic and can change frequently. I need to ensure that ...

Obtaining array value in JSON and incorporating it into a datatable

I have the following JSON data: { "aaData": [ [ { "displayValue": "Home Page", "link": "http://somelink.com" }, "London", "1983" ], [ { ...

Using Ionic/Angular ion-datetime with specific conditions

In my Ionic app, I have a datetime picker where users can select a time, but with one condition: If the hour is equal to '21', then the minutes must be set to '00' (not '30'). For all other hours, the minutes can be either &ap ...

Creating a visualization of a text file containing a combination of strings and integers on the same lines

Working on plotting a graph using a txt data file with this arrangement: {"alpha": 77.6, "beta": 135, "gamma": 342, "delta": 86.3} {"alpha": 77.3, "beta": 140, "gamma": 332, "delta": 82.3} ...... (300++ lines below with similar setups) A typical table ...

Exploring the Mathematical Capabilities of jQuery

I have a question regarding a jQuery code that retrieves the price of Bitcoin from a JSON API and displays its current value in euros. I am interested in converting this to another currency, such as Danish Crown or any other. Essentially, my query is whe ...

Restrict the object field type to an array by analyzing control-flow for accessing elements within brackets

Enhancements in type narrowing using control-flow analysis for bracket element access have been introduced in TypeScript 4.7. One thing I'd like to do is verify if the accessed field is an array or not. Currently, the type guard seems to be ineffecti ...

Suggestions for the structure of log information in the REST api format

Looking for a solution that can handle log data efficiently? Imagine having an api like logs?from=1/1/15 that returns all log lines from a specific date, but the problem is dealing with potentially massive amounts of data. Parsing it to a DOM using xml/jso ...

Overlapping Issue with Angular Bootstrap Dynamic Dropdown Menu

I'm currently working on creating a dynamic menu using Angular and Bootstrap for Angular. My main issue right now is that the submenus are overlapping each other when displayed on the page. To tackle this problem, I started off by referring to the ex ...

Showing data in a ListView with JSON elements divided by separators

I am looking for a solution to format JSON data into a ListView where each outermost object serves as a heading. The desired format should include dividers for "Company A" and all its projects, followed by a divider for "Company B" and its respective proje ...

Clear out the existing elements in the array and replace them with fresh values

Within my Progressive Web App, I am utilizing HTTP requests to populate flip cards with responses. The content of the requests relies on the selected values. An issue arises when I choose an item from the dropdown menu. It triggers a request and displays ...

Incorporating JSON objects into MySQL through a For Each loop - Checkbox Selections

My attempt to update the table (auth_users) with checkbox values using QueryBuilder and the provided code is not functioning correctly for the checkboxes on my form. I suspect that the issue lies in $key, "'".$value."'" not matching the DB field ...

What are the consequences of relying too heavily on deep type inference in React and Typescript?

In the process of migrating my React + Javascript project to Typescript, I am faced with preserving a nice unidirectional flow in my existing code. The current flow is structured as follows: 1. Component: FoobarListComponent -> useQueryFetchFoobars() 2 ...

Can you provide guidance on how to successfully transfer an array of JSON objects from the script section of an HTML file to the JavaScript

My webpage contains an array of JSON objects that I need to send to the server. The array, stored in a variable called results, appears normal when checked in the console before trying to POST it. Here is a sample of the data: 0: {id: 02934, uName: "Ben", ...

How to integrate ngx-bootstrap Static Modal into a personalized Angular 4 component

I have been trying to utilize the static modal feature from ngx-bootstrap in my Angular 4 project. When I directly include the modal on a web page, it works perfectly fine. However, when I try to include it in a component's templateUrl, it causes the ...

Using Typescript to incorporate Next.js on Firebase Functions

I'm currently working on deploying a Next.js application to Firebase Functions. import next from 'next' import {https} from 'firebase-functions' const server = next({ dev: process.env.NODE_ENV !== 'production', conf: ...

jQuery text replacement formatting

I need to strip parentheses and spaces from a field retrieved from JSON data. My initial approach was: '+myleads.Phone.replace(/(/g,'')+' However, repeating this process for each replacement seems cumbersome. Is there a simpler solut ...