Navigating json data in angular 6

I retrieved a JSON object in the following format

 response = [
{
  'a': [
    {
      'b': [
        {
          'c': [
            {
              'name': 'abc',
              'value': 900
            }
          ]
        }
      ]
    }
  ]
},
{
  'a': [
    {
      'b': [
        {
          'c': [
            {
              'name': 'abc',
              'amount': 900
            }
          ]
        }
      ]
    }
  ]
}
];

Now, I am trying to iterate through the object as shown below

this.response.forEach(
    (event) => {
      event.a.forEach(
          () => {

          }
      );
    }
)

However, while compiling, an error message is thrown

error TS2349: Cannot invoke an expression whose type lacks a call signature. Type '((callbackfn: (value: { 'b': { 'c': { 'name': string; 'value': number; }[]; }[]; }, index: number...' has no compatible call signatures.

Is there any solution for the above error? Thank you in advance.

Answer №1

Here is a simple way to access the properties c.name and c.amount

response.forEach(element => {
      element['a'].forEach(a => {
           a['b'].forEach(b => {
               b['c'].forEach(c => {
                     console.log(c.name);
                     console.log(c.amount);
               });
            });
      });
 });

Link to JSFiddle for reference: https://jsfiddle.net/jpwga2du/

Answer №2

for (let element1 of this.response) {
  for (let element2 of element1.a) {
    for (let element3 of element2.b) {
      element3.c.forEach(element4 => {
        alert(element4);
      });
    }
  }
}

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

Changing the value of a textarea in Angular forms using JavaScript

Having trouble with Angular forms? Try this: document.querySelector(TEXTAREA_SELECTOR).value = "some text" Methods like .title, .name, or .innerText don't seem to work. Consider trying these: document.querySelector(TEXTAREA_SELECTOR).dispa ...

Is it possible for a voiceover artist to initiate API requests?

As I work on the registration feature of my application, I am faced with the requirement that email addresses must be unique in the database. Since I am responsible for the front-end development, I am considering creating a Value Object (VO) that can make ...

When the browser is refreshed in Angular, the default root component will show up instead of the one specified in routes

I'm facing an issue with browser refresh on my Angular application. Every time I reload the page, either by refreshing the browser or entering a URL, the app redirects to the "/" route. Despite trying various solutions, none seemed to resolve the iss ...

Error: script took too long to execute, no response received within 11 seconds

During my integration test, I encountered an error message saying Failed: script timeout: result was not received in 11 seconds To investigate further, I navigated to the Chrome browser performance tab and noticed several yellow indicators showing scripti ...

Encountered an unexpected error while attempting to integrate my custom npm library "MyModule" into my Angular 2 project

I have created my own library which consists of one module and one component. After compiling my library, I add it to my main project using the following command: npm link ng-shared Next, when I attempt to import SharedModule in my module file as shown b ...

What is the best way to activate an <ion-datetime> with an <ion-button>?

Im currently attempting to execute the following action: I would like to select only the month and year using the example below: <ion-datetime presentation="month-year"></ion-datetime> However, I do not wish for this label to be vis ...

Angular Material Progress Spinner is static and not animated

I've been attempting to incorporate an indeterminate spinner from Angular Material. After reviewing the stack blitz example provided on their official website https://stackblitz.com/angular/nkabnxaenep, I carefully compared the package jsons and could ...

Transform Observable RxJS into practical results

In a straightforward scenario, I have an upload action on the page that looks like this: onUpload$: Subject<SomeUpload> = new Subject<SomeUpload>(); uploadAction$: Observable<Action> = this.onUpload$.map(entity => this.someActionServi ...

Next.js API routes encountering 404 error

I am encountering an issue with calling my route API (404) in my new nextjs project. The route API can be found at src/app/api/speed.js Within my page src/app/page.tsx, I have the following code snippet: fetch("api/speed").then(res=>res.json ...

Angular 2: How to Avoid Exceeding Maximum Call Stack Size with Eager Loading

I'm facing an issue with preloading all of my child route modules. In my root routing module, I have the following configuration: RouterModule.forRoot(appRoutes, { preloadingStrategy: AppCustomPreloader }) The structure of AppCustomPreloader is as f ...

Leveraging Angular 2 Service with the Power of RxJS BehaviorSubject or EventEmitter

Being new to Angular 2 and RXJS, I find myself faced with a challenge involving a custom header component that has 2 triggers (buttons) meant to activate 2 distinct navigation directives in different areas of the application. To address this issue, I have ...

In Angular 17, is there a way to trigger a component's method when a Signal is modified?

Our component is designed to monitor signals from a Service: export class PaginationComponent { private readonly pageSize = this.listService.pageSize.asReadonly(); private readonly totalCount = this.listService.totalCount.asReadonly(); readonly pag ...

What is the importance of having a reference path for compiling an AngularJS 2 project using gulp-typescript?

I wanted to modify the Angular Tour Of Heros project to utilize gulp from this Github Repository. This is the gulpfile.json file I came up with: const gulp = require('gulp'); const del = require('del'); const typescript = require(&apo ...

An unassigned variable automatically sets the disabled attribute to true on an input field

Is this behavior a problem or normal? Consider the following form structure: <form #form="ngForm" > <div> <label>field1</label> <input type="text" name="field1" [(ngModel)]="mainVar" [disabled]="someVar" /> ...

What is the best way to merge arrays within two objects and combine them together?

I am facing an issue where I have multiple objects with the same properties and want to merge them based on a common key-value pair at the first level. Although I know about using the spread operator like this: const obj3 = {...obj1, ...obj2} The problem ...

Generics causing mismatch in data types

I decided to create a Discord bot using DiscordJS and TypeScript. To simplify the process of adding components to Discord messages, I developed an abstract class called componentprototype. Here is how it looks (Please note that Generators are subclasses li ...

Tips for avoiding the transmission of className and style attributes to React components

Hey there! I'm working on a custom button component that needs to accept all ButtonHTMLAttributes except for className and style to avoid any conflicts with styling. I'm using TypeScript with React, but I've run into some issues trying to ac ...

How can we best store the component's state in the URL in AngularJS?

I am working with a reusable widget that has its own state. This state includes the content of the search bar (2), one or more select boxes (1), and the tree where the user can pick the currently active element (3). My goal is to create a locationManager ...

Is it possible for me to tap into the component creation process within the Angular Router?

Inspiration struck me when I realized the potential of adding a directive to the component designed for this particular route. It would elevate the functionality by letting me convey crucial information in a more declarative manner. Despite learning that ...

The installation of Angular CLI through npm has unfortunately encountered an error

After following the steps from this post to remove the old installation, I encountered an issue during the last step: [sudo] npm uninstall -g @angular/cli [sudo] npm cache verify [sudo] npm install -g @angular/cli During the final step, I faced difficult ...