Angular 13 implementation of a double-loop structure for fetching data from an API

I'm facing an issue with retrieving specific data fields label and svm from a JSON file. The desired fields are nested inside PORTFOLIO > REGROUPEMENT > ELEMENT.

You can access the JSON file here.

img(1)

I've attempted to display the data using the Google Chrome console.

getTitles(mode: PortfolioModeEnum): void {
    this.portfolioValue = 0;
    this.lines = [];
 
    this.service.getPortfolios(mode).pipe(
      takeUntil(this.unsubscribe$)
    ).subscribe((res: any) => {
      if (res.RETURNCODE === ApiResponseCodeEnum.Ok) {
        console.log("Test => " + res.REGROUPEMENT[0].ELEMENT[0]);
   }
        
    });
  }

Encountered error message:

core.mjs:6484 ERROR TypeError: Cannot read properties of undefined (reading '0')

img(2)

Struggling with data retrieval in a nested loop for LABEL and SVM.

portfolio.response.ts

export interface PortfolioResponse extends ApiResponse {
    PORTFOLIO: {
        VALPTF: number;
        DETAILS: {
            ACCOUNTLAB: string;
            ACCOUNTTYPE: string;
            LABEL: string;
            ACCOUNTPHYSICAL: string;
        };
        REGROUPEMENT: InstrumentRegroupement[];
    }
}
 
export interface InstrumentRegroupement {
    TYPEVALUE: number;
    ASSETCATLABEL: string;
    CURRENCY: string;
    AMOUNT: number;
    PERCENTAGE: number;
    ELEMENT: {
        LABEL: string;
        STOCK: string;
        SVM: number;
        COUPONNUMBER: number;
        ISINCODE: string;
        MARKETPLACE: string;
        ...
    }[];

...

EDIT

enter image description here

EDIT 2

TS

getTitles(mode: PortfolioModeEnum): void {
    this.portfolioValue = 0;
    this.lines = [];
 
    this.service.getPortfolios(mode).pipe(
      takeUntil(this.unsubscribe$)
    ).subscribe((res: any) => {
      if (res.RETURNCODE === ApiResponseCodeEnum.Ok) {
        const data = res.PORTFOLIO.REGROUPEMENT.map((regroupment) => {
          return regroupment.ELEMENT.map((element) => ({
            label: element.LABEL,
            svm: element.SVM,
          }));
        }).flat();

   }
        
    });
  }

HTML

Your assistance is greatly appreciated.

Answer №1

If you are looking for a simple way to extract the label and svm fields from a hierarchy structure without dealing with the rest of the details, you can utilize the array.map() method to retrieve the specific keys at each level. Then, by using array.flat(), you can flatten the structure.

const information = data.PORTFOLIO.REGROUPEMENT.map((regroupment) => {
  return regroupment.ELEMENT.map((element) => ({
    labelName: element.LABEL,
    svmValue: element.SVM,
  }));
}).flat();

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

Having trouble with VSCode/tsconfig path configurations, as the files are being fetched but still receiving a "Module not found" error in the editor

Since I began working on this project, I've been encountering a peculiar issue. When importing modules and files in my Angular components/classes using import, I face an error in VSCode when the paths use the base path symbol @. Strangely enough, desp ...

Excess whitespace found in string within mat-option

Every time I retrieve text from the mat-option, I notice an additional space at the end of the string. This causes my assertion to fail when trying to compare it with the expected value. This issue is new to me, and I'm unsure how to address it. Why ...

Verify user authentication

My journey with learning Angular 2 has hit a roadblock. I have set up routes in my application as follows: const appRoutes: Routes = [ {path: 'start', component: StartComponent, children:[{path: '' }, { path:&ap ...

Retrieve information using an asynchronous pipeline once the screen is fully loaded

In my table component, I have integrated functionality for data reloading and filtering. These actions are powered by Subjects: private fetchFromServer$ = new Subject< void >(); private filter$ = new Subject< void >(); The data fetching proces ...

Encountering an issue with Angular build in Docker: [ERR_STREAM_DESTROYED] - Write function cannot be called after a stream

Below is the docker file I'm using to build my Angular project: FROM node:12-buster-slim as build-step RUN mkdir -p /app COPY . /app WORKDIR /app RUN chmod 777 -R /app RUN npm install ARG configuration=production RUN npm run build -- --output-path=./ ...

Does combineLatest detach this from an angular service function?

Check out this test service on Stackblitz! It utilizes the combineLatest method inside the constructor to invoke a service method: constructor() { console.log("TEST SERVICE CONSTRUCTED") this.setParameters.bind(this) this.assignFixedParamete ...

Is it feasible to incorporate an Angular environment variable into an SCSS file?

I'm trying to come up with a solution for dynamically compiling my `scss` based on different environment profiles. Each location where my app will be installed has a different theme, but the CSS remains the same. The only thing that needs to change is ...

A React component featuring a nested map function should always include a "unique key" prop for each element

I am trying to figure out how to assign a proper Key Value in this component: {var.map((building, index) => { const handles = building.buildingVertices.map((point) => { return ( <DrawingHandle key={`${i ...

Unleash the power of drag-and-drop functionality with cdkDrop

I am currently tackling a project that requires the implementation of a drop zone functionality where elements can be dragged from a list and dropped in a zone for free movement. I intend to utilize a cdkDropList for the zone due to its comprehensive list ...

Using mat-select along with formControl to establish the default value

I'm struggling to assign a default value to my formControl, but it doesn't seem to be working as expected. select-hint-error-example.ts export class SelectHintErrorExample { animalControl = new FormControl('', [Validators.required]) ...

Exploring Angular 2's Routing Features Across Different Cultures

Looking to integrate culture into all routes in my application utilizing RC4. How can I adjust the existing routes to achieve this objective? export const routes: RouterConfig = [ ...ItemRoutes, ...LibraryRoutes, { path: '', redirectTo: 'd ...

Angular2 application encounters issue with target attribute being overlooked by Chrome

I am trying to implement a link in an iframe following the instructions on W3Schools: <iframe height="300px" width="100%" src="demo_iframe.htm" name="iframe_a"> </iframe> <p><a href="http://www.w3schools.com" target="iframe_a">W3S ...

When I try to integrate Three.js into my React application, it mysteriously causes my root HTML element

While attempting to utilize Three.js in Typescript react, I successfully rendered a Dodecahedron figure along with random stars. However, my intention was to incorporate some markup into my Three.js scene using React. Unfortunately, when I render the Three ...

Using Meteor methods in a Meteor and Ionic application: A guide

After building the web app with Meteor, I am now looking to develop a new app utilizing both Meteor and Ionic technologies. My goal is to leverage the existing Meteor methods in my Ionic app without duplicating efforts for mobile development. Any suggestio ...

The intersection observer is unable to track multiple references simultaneously

Hey there, I've been using a switch statement in my Next.js project to dynamically serve different components on a page. The switch statement processes a payload and determines which component to display based on that. These components are imported dy ...

Ways to eliminate additional data points on the x-axis in Highcharts

I'm currently using Highcharts to plot data for specific ID's, but I'm experiencing a display issue where extra data points are showing up on the x-axis. I only want to show certain data points on the x-axis and am not sure how to remove the ...

How can I replace any non-alphanumeric characters in a string with an underscore using JavaScript or TypeScript?

There is a unique string generated from an external data source that I cannot manage. The system above me necessitates the IDs to adhere to this rule: "Field names should start with a letter and can solely consist of letters, numbers, or underscores (&apos ...

Playing a single media object from a group of multiple objects in Ionic

On the screen, there are three Ionic-native media objects available. I have written a code that allows me to play the selected object. play(filename) { this.curr_playing_file = this.createAudioFile(savfilename); this.curr_playing_fil ...

Exploring the correct navigation of page objects through Protractor using TypeScript

I'm working on setting up a protractor test suite with TypeScript and running into an issue involving chaining of pageObjects for multiple pages. I haven't seen any examples that deal with this specific scenario. I've simplified the example ...

Adjust the color of an SVG icon depending on its 'liked' status

In my React/TypeScript app, I have implemented an Upvote component that allows users to upvote a post or remove their upvote. The icon used for the upvote is sourced from the Grommet-Icons section of the react-icons package. When a user clicks on the icon ...