A Guide to Iterating Through Arrays of Objects Using TypeScript

Currently, I am engrossed in an Angular project where I am fetching an object containing an array of objects from an API.

The object being passed to the API as a parameter through my service is called "reportData".

Here is an example of the data retrieved from the API:

https://i.stack.imgur.com/PV0Nh.png

My goal is to iterate through the array, extract the product names and average quantity ordered, but I am unsure how to accomplish this task.

One aspect that confuses me is that upon examining the attached screenshot, it seems like the result is an object containing an array of objects. This might be why I am having trouble iterating through it, since technically it is an object and not an array.

I attempted something like this (where retrievedData is the array of objects), but encountered the error "Cannot read property 'forEach' of undefined":

retrievedData: any;

this.retrievedData.array.forEach(element => {
          this.productNames.push(element.ProductName);
        });

To retrieve the data, I utilize a service:

onSubmit(form:NgForm)
  {

    this.service.postReportData().subscribe(
      res => {
        this.retrievedData = res;
        console.log(this.retrievedData);
      },
      err => {
        console.log(err);
      }
    );

  }

Any assistance on this matter would be greatly appreciated!

Answer №1

thus, when you retrieve the data, it will come in an object that contains an array of objects

ensure that your res is of the following type

type Item = {
  ProductName: string;
  AverageQuantityOrdered: number;
  ProductOrders: unknown[];
}

type RetrievedData = {
  reportData: Item[];
}

you can then declare RetrievedData as the type for your retrievedData variable

retrievedData: RetrievedData

instead of using any

by doing this, accessing retrievedData.reportData will give you the desired array.

Answer №2

Big thanks to all for the valuable comments!

I managed to make it work using this code snippet:

onSubmit(form:NgForm)
  {
    this.service.postReportData().subscribe(
      res => {
        this.retrievedData = res;

        this.retrievedData.reportData.forEach(function (item) {
          console.log(item);
          console.log(item.ProductName);
          console.log(item.AverageQuantityOrdered);
        });

      },
      err => {
        console.log(err);
      }
    );

  }

Had to loop through reportData as it contained an array of objects, not retrievedData.

Thanks once again for the assistance!

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

Issue with Firestore rule functionality not meeting expectations

I have set up the following rule on Firestore: service cloud.firestore { match /databases/{database}/documents { match /items/{itemid} { allow read, write: if request.auth.uid == resource.data.owner; } } } When initializing my collec ...

ConcatMap in RxJS processes only the last item in the queue

Currently, I am implementing NGRX with RXJS. Within the effects layer, I am utilizing a concatMap to organize my requests in a queue fashion. However, once the latest request is finished, I aim to execute the most recent item added to the queue instead of ...

Transmitting data from Angular to .NET Core for seamless integration

I have been attempting to send an xls or any other file from my angular application to a .NET core controller, but none of my methods seem to work... Below is my component where I call my service upon button click: handleFileInput(file: FileList) { this. ...

Arranging Two-Dimensional Arrays in C

I have encountered an issue with my code that involves a segmentation fault when printing statements are executed. The code snippet provided below demonstrates the problem I am facing: int rows(int board[][9]){ int badUnits = 0, i = 0, n = 9, j, z = 0 ...

The user type is not yet loaded from Firestore when the view is rendered

I am currently in the process of developing an Ionic - Angular application that allows hospital patients to submit requests to nursing staff, who can then view the assigned requests based on the patient's room. Nurses have access to all requests, whil ...

Combining Firebase analytics with an Ionic 3 application using the Ionic Native plugin

I placed the GoogleService-Info.plist file at the root of the app folder, not in the platforms/ios/ directory. When I tried to build the app in Xcode, an error occurred in the following file: FirebaseAnalyticsPlugin.m: [FIROptions defaultOptions].deepLin ...

The 'MutableRefObject<null>' type is lacking the following properties that are present in the 'Element' type

I'm eager to implement intersection observer in my React Typescript project. (https://www.npmjs.com/package/react-intersection-observer) However, I encountered an issue with setting the root: const root = useRef(null); const { ref, inView, entry } ...

Attempting to invoke a promise within a function yields an error message stating that it lacks call signatures

Recently, I came across this interesting class: export class ExponentialBackoffUtils { public static retry(promise: Promise<any>, maxRetries: number, onRetry?: Function) { function waitFor(milliseconds: number) { return new Pr ...

The issue in Angular2 viewmodel where the boolean value fails to update the *ngIf template

I'm seeking assistance with an unusual issue in my Angular2 and Typescript application. Within my template, I have the following HTML utilizing ngIf: <div *ngIf="loading" class="row"> <div class="small-3 small-centered columns" > ...

Conceal certain components when a user is authenticated

Below is the content of my app.component.html: <nav class="navbar navbar-expand-lg navbar-light bg-light"> <div class='container'> <ul class="nav navbar-nav"> <li class='nav-item'> <a clas ...

Comparing the length of an array to whether the length of the array is greater than

What distinguishes checking an array's length as a truthy value from verifying that it is greater than zero? In simple terms, is there any advantage in utilizing one of these conditions over the other: var arr = [1,2,3]; if (arr.length) { } if (arr ...

Dockerized Angular CLI app experiencing issues with hot reload functionality

My existing angular cli application has been dockerized with the following setup: Dockerfile at root level: # Create a new image from the base nodejs 7 image. FROM node:7 # Create the target directory in the imahge RUN mkdir -p /usr/src/app # Set the cr ...

Do you have any suggestions for optimizing an Angular 15 reactive form that gets filled with data from an API?

Creating an Angular 15 Reactive Form with FormGroup As I delve into the documentation to construct a form with 4 inputs that are populated with data retrieved via GET requests and then updated upon submission through PUT requests, I find that it is functi ...

Unused Angular conditional provider found in final production bundle

Looking for a way to dynamically replace a service with a mock service based on an environment variable? I've been using the ?-operator in the provider section of my module like this: @NgModule({ imports: [ ... ], providers: [ ... en ...

What is the process for waiting on RxJS data and how should it be retrieved?

I am faced with a situation where I need to create a user through a function, but before proceeding with the creation process, I have to verify whether another user with the same userName is already present in the session: public createUser(form: FormGroup ...

Is it possible to access the passed arguments in the test description using jest-each?

Utilizing TypeScript and Jest, consider this sample test which can be found at https://jestjs.io/docs/api#testeachtablename-fn-timeout it.each([ { numbers: [1, 2, 3] }, { numbers: [4, 5, 6] } ])('Test case %#: Amount is $numbers.length =&g ...

The 'npm update' command seems to be failing when attempting to update dependencies within Angular2

I am looking to upgrade the outdated dependencies in my Angular 2 project. Upon running npm outdated, I identified several dependencies that need updating. However, when I attempt to update them using the npm update command, it does not seem to work as exp ...

The sequence for initializing properties in Typescript

In my Typescript code, I have 2 classes named A and B. Class B inherits from class A, where class A's constructor calls a function called init, and class B overrides the init function. a.ts export default class A { constructor() { this.ini ...

The FormGroup instance does not return any input method when using the get input function

I am facing an issue where a custom error message should only display if the input for foo is invalid. However, it seems like the line of code myForm.get('foo') is returning null. Below is the simplified version of component.html: <form [for ...

@vx/enhanced responsiveness with TypeScript

I am currently utilizing the @vx/responsive library in an attempt to retrieve the width of a parent component. Below are snippets from my code: import * as React from 'react' import { inject, observer } from 'mobx-react' import { IGlob ...