Transform the API response into a map in Angular version 16

When I receive a JSON response from a Java server, the structure looks like this:

{
  "summary": {
    
  },
  "runs": {
    "key_1": {
      "object_1": {
        
      },
      "object_2": {
        
      }
    },
    "key_2": {
      "object_1": {
        
      },
      "object_2": {
        
      }
    }
  }
}

The service function is defined as follows:

public getDetailsV2(id: number): Observable<MyClass> {
    return this.httpClient.get<SimulationDetailedResponseV2>(
      'url_to_endpoint'
    );
  }

Calling the service function like this:

this.service.getDetailsV2(1).subscribe({
      next: (details) => {
        this.details = details;
      }
    });

However, when I try to use map methods on this.details, I encounter errors. For example, attempting to retrieve the first entry with:

this.details.runs.entries().next().value;
results in:
ERROR TypeError: this.details.runs.entries is not a function

The MyClass class is structured like this:

export class MyClass {
  runs: Map<string, AnotherObject>;
}

Why isn't the response.runs automatically converted to a map? How can I manually convert it?

Answer №1

If you take a look at the code snippet below, you can utilize Object.entries to convert an object into a map. In JavaScript, it's important to note that this conversion needs to be done manually as the language does not handle it automatically.

const data = {
  "summary": {
        "test": 1,
  },
  "runs": {
    "key_1": {
      "object_1": {
        "test": 1,
      },
      "object_2": {
        "test": 1,
      }
    },
    "key_2": {
      "object_1": {
        "test": 1,
      },
      "object_2": {
        "test": 1,
      }
    }
  }
};

const neededMap = new Map(Object.entries(data.runs));
console.log(neededMap.entries().next().value);

By integrating this code snippet into your own project, you'll achieve similar functionality as shown below:

this.service.getDetailsV2(1).subscribe({
  next: (details) => {
    details.runs = new Map(Object.entries(details.runs));
    this.details = details;
  }
});

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

What is the proper way to update a dropdown value in a React JS component?

Can you please guide me on how to assign a value in a dropdown in react js? I am retrieving the dropdown data after a delay of 3000 milliseconds and then I need to set a value in the dropdown. const App = ({ children }) => { const val = "ax"; const ...

What is the best way to transfer information from an old JSON file to a new JSON file using JavaScript

I have a JSON file and I need to extract the content of "data" where the provider is "AXIS DATA" into a new JSON file. How can this be achieved? Here's what I've attempted: First, I convert it using JSON.parse and then search for the desired da ...

Is there a way to create a Vue component that can process dynamic formulas similar to those used in

I am looking to create a component that has the ability to accept different formulas for computing the last column. The component should use these formulas in Vuex getters to store the total state values passed to it. Here are the specifications for the c ...

Tips for preventing special characters from being entered into a Kendo grid input column

Is there a way to prevent users from entering special characters into the description column of my Kendo grid? The column field setup is as follows: { field : "myDesc", width : 200, title : "My Description"} I have attempted the following approach so far ...

Streaming HTTP content on a domain secured with HTTPS using HTML5

Is it possible to stream HTTP on an HTTPS domain without triggering browser security errors? By default, the browser tends to block such requests. I rely on the hls.js library for desktop support with .m3u8 files. When I play content directly (on mobile o ...

Combining Various Data Types in a Flexible List

I'm looking for a way to dynamically add rows to a table. Right now, I have the input type on the server (whether it's int, bool, string, etc), but I want to know how to implement a field accept combobox. Here is the code in cshtml: <tr ng-r ...

Use ASP.NET MVC to pass data from an action to an AJAX call and utilize it in the success function

I have a custom ResultOfOperation class that I use to retrieve details about an activity: public class ResultOfOperation { public string Message1 { get; set; } public string Message2 { get; set; } public string Message3 { get; ...

Exploring ways to retrieve texture dimensions using Three.js

Can someone please advise me on how to retrieve the dimensions of a texture? I have set my texture using the following line of code: const texture = THREE.ImageUtils.loadTexture(src) Do I need to load the image in order to obtain its dimensions (and can ...

Avoid Conversion of HTML Entities in Table Cells

<table> <tr> <td>&gt;</td> </tr> <tr> <td>&&#xfeff;GT</td> </tr> </table> In the code snippet above, I have table cells containing HTML entities. A re ...

AJAX should prevent page refresh, but sometimes it forces it

This AJAX test page is a simple demonstration using JQuery. When the page is loaded, it displays a button (BUTTON1). Upon clicking on BUTTON1, it will execute react.php using script.js. The react.php will then replace BUTTON1 with BUTTON2 using a span elem ...

When using Remix v2.8.1, the function useRouteLoaderData can return undefined if an error boundary is present in the root.tsx file

In my project, I have a loader in the root.tsx file and a component called 'Nav' which utilizes the loader data using the useRouteLoaderData hook. For instance, const data = useRouteLoaderData('root') as needed. <body> < ...

Using Vue.js to make an AJAX request to an API that returns a list in JSON format

I am attempting to utilize an AJAX call with the free API located at that returns a list in JSON format. My goal is to display the result on my HTML using Vue.js, but unfortunately, it doesn't seem to work as expected. This is my JavaScript code: va ...

Incorporating a JSX Component within a TSX Component results in a compilation error

Recently, I encountered an issue with my typescript-react component named ContractExpenses. The problem arose when I tried to integrate a JSX component called DynamicSelector within it, resulting in the following error: https://i.sstatic.net/BMMir.png Be ...

Parent window login portal

I have just started learning how to program web applications, so I am not familiar with all the technical terms yet. I want to create a login window that behaves like this: When a user clicks on the Login button, a window should pop up on the same page t ...

Incorporating external JavaScript into a Rails application

Having trouble with the syntax on this simple problem. Struggling to find examples of externally linked files, all solutions online involve storing a local copy instead. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" typ ...

What is the best approach for running a database query using the value selected from a form dropdown?

Currently, my application server is ColdFusion and I am using SQL Server for the database. Within a select form element on my webpage, users can choose from a list of vehicles such as Volvo S60, BMW M6, and VW Jetta. Once a user selects a vehicle, I need ...

Creating a rectangular pyramid using three.js r68: a step-by-step guide

Currently working on r68, I'm in search of a modern example showcasing the creation of a rectangular pyramid that will allow me to implement THREE.MeshFaceMaterial(). Many existing examples are outdated and lead to errors with my current setup. My re ...

Serve Webpack bundle on various routes - Express Way

I recently completed a web application using an Express backend and React frontend. Upon sending a request to the Express server, it undergoes a process where the URL is checked against the backend routes. If there isn't a match, the React bundle gen ...

Explore the functionality of the router replacement feature in Next.js

Currently, I am in the process of learning Next.js, but unfortunately encountered an error. import { useRouter } from "next/router"; export default function Auth() { const router = useRouter(); const root = router.query.auth; if (root !== ...

Tips for obtaining and storing multiple inputs within the same readline.question prompt in separate variables

Seeking to gather multiple user inputs in a single readline question and assign them to different variables? You're not alone! Ran into this challenge myself while trying to figure out the solution. Code import * as readline from 'node:readline&a ...