How can I retrieve Map<K, V> values from JSON in a DTO?

I am currently dealing with a situation where I have nested DTOs as follows:

export class firstDTO {
    public data: secondDTO;
}

export class secondDTO{
    public data: Map<Color, thirdDTO>;
}

When I receive the JSON data from the backend and try to print it to the console, I am facing difficulties accessing the values inside the Map. I keep encountering undefined errors.

private getJsonData(): void {
this.service.getJSON()
  .subscribe((jsonData: firstDTO) => {
    this.things = jsonData;
  });
}

The way I would ideally like to access a property of Color is by using this syntax:

this.things.data.data.key[0].property

However, I understand that this approach won't work, so I am seeking assistance in resolving this issue.

Answer №1

If the retrieved JSON matches the type of the first DTO and you have the key for the third DTO, you can access it as shown below in the print method. Otherwise, you can iterate through data.first.second to return a map with keys and values as ThirdDTO. The maps can be iterated using a foreach loop.

export class AppComponent {
print(data:first){
console.log(data.first.second.get('color'));
}
}

class first{
first:second;
}

class second{
second:Map<string,third>;
}

class third{
third:string;
}

Answer №2

JSON does not contain Map objects. It seems like what you have is an object meant to be accessed with strings in the form of LocationDTO(...). To declare this, do the following:

export class secondDTO{
    public data: {[s: string]: thirdDTO};
}

If key[0] follows the correct format as a string, then you should use

this.things.data.data[key[0]].property
to retrieve a property from the third DTO. Make sure to notice the extra square brackets instead of a dot.

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 a Button with Icon and Text in TypeScript: A step-by-step guide

I attempted to create a button with both text and an icon. Initially, I tried doing it in HTML. <button> <img src="img/favicon.png" alt="Image" width="30px" height="30px" > Button Text ...

Transfer text between Angular components

Here is the landing-HTML page that I have: <div class="container"> <div> <mat-radio-group class="selected-type" [(ngModel)]="selectedType" (change)="radioChange()"> <p class="question">Which movie report would you like ...

turning off next.js server side rendering in order to avoid potential window is undefined issues

I am currently managing a private NPM package that is utilized in my Next.js project, both of which are React and Typescript based. Recently, I integrated a graph feature into the NPM package and encountered an issue where any reference to window within t ...

I'm having trouble getting forkJoin to trigger

As I create a guard in Angular, I am faced with the challenge of making two distinct HTTP requests and then deciding whether to continue based on both responses. After some research, I learned that forkJoin is the recommended approach for this task, but fo ...

How would you classify a function that accepts an input of T<A>[] and returns T<A[]>?

Here are a few instances const f = <L, R>(xs: Either<L, R>[]): Either<L, R[]> => { throw new Error('Not Implemented') }; const f = <T>(xs: Promise<T>[]): Promise<T[]> => { throw new Error('Not Imp ...

Angular-6 Issue: Default Value Not Displaying in Drop-Down List

I am attempting to bind an array into a list. The binding part is functioning correctly, but the default value of the drop down is not displaying. Initially, the array does not contain any values. Here is the code snippet: <select (change)="select($ev ...

Angular HTTP post call is failing to redirect to the correct URL

https://i.sstatic.net/CzSuQ.pngCan someone assist me in resolving the http post problem? I am facing an issue where the url validation is not working correctly. Even when localhost:8084 is up and running, the error section is triggered, and the same happen ...

Having trouble adding @angular/fire to my Angular project

Having trouble adding Firebase authentication to my Angular project, specifically when running npm install @angular/fire. I keep encountering the following error: > npm ERR! code ERESOLVE > npm ERR! ERESOLVE unable to resolve dependency tree > ...

BaQend is all set to go as it initializes, just make sure to verify the user's login

Currently, I am utilizing BaQend and Ionic2 to implement certain tasks at the start of my application. 1. Database Readiness Instead of repeating this process on every page: ionViewCanEnter(): Promise<baqend> { // Verify Baqend SDK readine ...

Transferring dynamic parameters from a hook to setInterval()

I have a hook that tracks a slider. When the user clicks a button, the initial slider value is passed to my setInterval function to execute start() every second. I want the updated sliderValue to be passed as a parameter to update while setInterval() is r ...

What are some strategies for circumventing the need for two switches?

My LayerEditor class consists of two private methods: export class LayerEditor { public layerManager: LayerManager; constructor() { this.layerManager = new LayerManager(this); } private executeCommand() { ...

In Typescript, is it possible to utilize the value from a particular key in a type declaration as the type for another key within the same declaration?

Consider a scenario where I am designing a Variable type that includes a key named type with a value of type string. Is there a method to extract the value from the type key and utilize it as the type for another key within the declaration, without resorti ...

display a discrete delete button when pressing a button within ng-bootstrap

My current setup uses ng-bootstrap with Angular4. Image https://i.sstatic.net/83UhP.png In the interface, a checkbox button is used to show responses fetched from the backend. By clicking the button, the x button disappears along with other elements belo ...

Sort out the information in the table

Seeking assistance on how to filter a table based on certain conditions. Refer to the sample image provided in the link below: https://i.sstatic.net/Egvj6.png Here is the code I have attempted: this.reportData.filter(it => { if ( ...

Next.js App experiences a 404 Error when attempting to access the Auth0 Endpoint "api/auth/me"

Following a tutorial, I integrated my Next.js App with Auth0 successfully. However, after logging in and out, I encountered an issue where the user object is not returned when trying to display user information on the page post-login. Both the Profile.js p ...

Guide on importing all exported functions from a directory dynamically in Node.js

In my file main.ts, I am looking to efficiently call imported functions: import * as funcs from './functions'; funcs.func1(); funcs.func2(); // and so forth... In the same directory as main.ts, there is a functions directory containing an index ...

Tips for transferring all attributes from an Angular component to a template

I have a unique custom Angular 4 component where I utilize <img> as a template. The component is identified by the selector i-image, resulting in it being displayed in the UI as shown below: <i-image _ngcontent-c0="" alt="this is alt" ng-reflect- ...

After selecting an item, the Next UI navbar menu seems to have trouble closing

Having trouble with the navbar menu component not closing when an option is selected from the menu. The menu does open and close successfully within the menu icon. I attempted to use onPress() but it doesn't seem to be working as expected. "use c ...

The process of concealing or eliminating mat-options after they have been selected in mat-select methods

Currently, I have a table that utilizes mat-table and I am incorporating dynamic rows by clicking a button. Among the columns in the table, there is one with a dropdown feature using mat-select which contains static options of mat-option. You can view a sa ...

The content inside the HTML body doesn't fully encompass the dimensions of the mobile screen

I am working on making my application flexible by using 100vw width and 100vh height for the components. Everything displays perfectly in any resolution on a computer browser, but when viewed on a mobile device, an empty background is drawn below the bod ...