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

Creating and Injecting Singleton in Angular 2

I have a custom alert directive set up in my Angular app: import { Component } from 'angular2/core'; import { CORE_DIRECTIVES } from 'angular2/common'; import { Alert } from 'ng2-bootstrap/ng2-bootstrap'; @Component({ sele ...

Error: Unable to access the 'visitStatement' property of an undefined object within Angular 2

Help! I encountered an error in my angular2 application. The error message says: TypeError: Cannot read property ‘visitStatement’ of undefined ...

Using type definitions in non-TS files with VSCode: A beginner's guide

My code is not in TypeScript, shown here: // foo.js module.exports = app => { // some logic here } I want to enhance my development experience by using TypeScript definition files to specify the type of the argument app, enabling VSCode to provide ...

Master the art of properly switching on reducer-style payloads in Typescript

Currently, I am dealing with two types of data: GenArtWorkerMsg and VehicleWorkerMsg. Despite having a unique type property on the payload, my Searcher is unable to differentiate between these data-sets when passed in. How can I make it understand and dis ...

Node.js is having trouble retrieving information from the SQLite database

Here's a simple code snippet I'm using to retrieve data from my sqlite database. Index.ts: import { Database } from './Class/database'; Database.checkIfExists("some ID"); Database.ts: export class Database { static sqli ...

Is it possible to integrate angular-bootstrap-datetimepicker with bootstrap3?

Looking for an accessible date picker solution for my project. The project is built on Bootstrap3, but the angular-bootstrap-datetimepicker has a dependency on Bootstrap4. Can I still integrate angular-bootstrap-datetimepicker with Bootstrap3? ...

What is the reason for calling Proxy on nested elements?

Trying to organize Cypress methods into a helper object using getters. The idea is to use it like this: todoApp.todoPage.todoApp.main.rows.row .first().should('have.text', 'Pay electric bill'); todoApp.todoPage.todoApp.main.rows.ro ...

Using React with an Array of Promises in Typescript

I have a function that looks like this: function queryProposals(hash:string) { let result = api?.query.backgroundCouncil.proposalOf( hash,(data1:any)=>{ let injectedData = data1.toPrimitive().args.account as InjectedAccou ...

Issue with merging JSON in Angular using RxJS

Seeking assistance with combining two JSON objects in an Angular application. JSON Object 1: { "level1": { "level2": { "level31": "Text 1", "level32": "Text 2", "leve ...

The Angular @HostListener beforeunload Event is a powerful way to handle

I've implemented the following code snippet in my main app.component.ts file within my Angular 17 project: @HostListener("window:beforeunload", ["$event"]) onTabClose($event: BeforeUnloadEvent) { $event.preventDefault(); ...

Retrieve the property values of `T` using a string key through the `in

Having trouble accessing a property in an object using a string index, where the interface is defined with in keyof. Consider the following code snippet: interface IFilm { name: string; author: string; } type IExtra<T extends {}> = { [i ...

The RouteParams encounter a problem because it is unable to resolve all parameters

I'm encountering an issue with the RC3 router. The error message I am receiving is: Can't resolve all parameters for RouteParams: (?). Below is my code: //route.ts import {provideRouter, RouterConfig} from '@angular/router'; import {H ...

Angular Material Slide-Toggle Takes Too Long to React

In my project, I am facing an issue with a control panel that contains an Angular Mat-Slide-Toggle element. Here is the code snippet: <mat-slide-toggle (change)="onQAStateDisplayChanged($event)">Display QA Status</mat-slide-toggle> When the c ...

Leverage Sinon's fakeServer in combination with promises and mocha for efficient

Having an issue here: I need to test a method that involves uploading data to an AWS S3 bucket. However, I don't want the hassle of actually uploading data each time I run my tests or dealing with credentials in the environment settings. That's w ...

Enhancing Angular functionality with the addition of values to an array in a separate component

I need help with adding a value to an array in the 2nd component when a button in the 1st component is clicked. I am working on Angular 4. How can I achieve this? @Component({ selector: 'app-sibling', template: ` {{message}} <butt ...

How can you utilize both defineProps with TypeScript and set default values in Vue 3 setup? (Typescript)

Is there a way to use TypeScript types and default values in the "defineProps" function? I'm having difficulty getting it to work. Code snippet: const props = defineProps<{ type?: string color?: 'color-primary' | 'color-danger&a ...

Angular Route seems unreachable

These are my guidelines for routes: export const appRoutes: Routes = [ { path: "", component: HomeComponent }, { path: '/signup', component: AppComponent }, { path: "**", redirectTo: "/" } ]; Upon attempting to access the URL: http ...

Creating a default option in a Select tag with React when iterating over elements using the map method

After learning that each element in the dropdown must be given by the Option tag when using Select, I created an array of values for the dropdown: a = ['hai','hello','what'] To optimize my code, I wrote it in the following ...

What is the best way to create a list using only distinct elements from an array?

If I have a collection of different colors: Red Blue Blue Green I aim to extract only the unique colors and store them in an array. Subsequently, I plan to incorporate each color from that array into an existing color list. The desired outcome would l ...

Exploring an array of objects to find a specific string similar to the one being

I recently developed a TypeScript code snippet that searches for objects in a list by their name and surname, not strictly equal: list = list.filter( x => (x.surname + ' ' + x.name) .trim() .toLowerCase() .sear ...