Generating a JSON list from a Map object utilizing an interface in Angular 9

The map in my project is generated using the countries-map plugin and includes data values. Here is an example of the data provided by the plugin:

mapData: CountriesData = {
  'ES': { 'value': 416 },
  'GB': { 'value': 94},
  'FR': { 'value': 255 }
};

This data is structured based on the following interfaces:

interface CountriesData {
  [countryCode: string]: CountryData;
}
interface CountryData {
  value: number;
  extra?: CountryExtraData;
}
interface CountryExtraData {
  [key: string]: number |string;
}

When my API returns data, it provides a map format like this:

{
  "countryInstallHistory": {
    "DZ": 1,
    "SN": 3
  }
}

In my Angular project, I am able to iterate through the list of countries using the following code:

for (let [key, result] of Object.entries(this.apkHistorDto.countryInstallHistory)) {
  console.log(key)
  console.log(result)
}

I am wondering how I can create a new map based on the data sent by my API, following the same interface structure. Any advice or guidance would be greatly appreciated. Thank you.

Answer №1

To solve this problem, I recommend utilizing the reduce method of arrays. Check out the demonstration below:

let data = {
  countryCodes: {
    US: 10,
    CA: 5,
  },
};
   
 const mappedData = Object.entries(data.countryCodes).reduce(
    (result, [code, count]) => ({...result, [code]: { count }}), {}
  )

console.log(mappedData);

Answer №2

Shall we implement a data conversion function similar to the one above?

function processData(data) {
  let _output = {};
  let output = data.regionData;
  for (let prop in output) {
    _output[prop] = { value: output[prop] };
  }
  return _output;
}

let data = {
  regionData: {
    CA: 4,
    MX: 6,
  },
};
console.log(processData(data));

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

Why is my Angular 2 app (TypeScript) not functioning properly?

My current project includes a component called EventListComponent import { Component } from 'angular2/core'; @Component ({ selector: 'el-events', templateUrl: 'app/events/event-list.component.html' }) export class E ...

utilize a modal button in Angular to showcase images

I am working on a project where I want to display images upon clicking a button. How can I set up the openModal() method to achieve this functionality? The images will be fetched from the assets directory and will change depending on the choice made (B1, ...

Incorporating numerous query parameters in Angular version 14

I am currently working on developing a multi-item filter feature for my application and I am faced with the challenge of sending multiple query parameters in the API request to retrieve filtered items. My main concern is whether there is a more efficient ...

When using `console.log`, the object is displayed correctly. However, an error occurs when

Here is the code I've been working on: function parseJSONData(jsonData){ var property, type, name, identifier, comment, content; for(property in jsonData){ switch(property){ case "type": type = jsonData[ ...

The output for each function is consistently the same for every record

Implementing a foreach loop to send data and display it in the success function of an AJAX call is functioning smoothly. Recently, I made a modification to the code by introducing a new data-attribute which contains the $creator variable. Here's how ...

The POST function isn't functioning correctly within the temp.js file

My issue with the post method: var newUser = { "user5" : { "name" : "john", "password" : "qwerty123", "profession" : "developer", "id": 5 } } app.post('/createUser', function (req, res) { // Reading existing use ...

Typescript MUI Autocomplete: Can you specify the parameter type of the PaperComponents function?

If you use MUI's Autocomplete, there is a property called PaperCompomponent that allows you to pass your own react component. This property is a function with properties as a parameter, which can then be used to pass on to your custom component. In T ...

Converting text to JSON format using Java (text as a list)

After making a call to an API, I have retrieved the following text: {"identified_faces_names": "[\"omar\", \"elhoussinep\"]"} However, when attempting to parse this text using JSONParse, I encountered the following exception: An ...

Numerous toggle classes available

Having the following HTML inside a <span> element: <span (click)="openLeft()"></span> A method in a @Component sets a boolean variable like so: private isOpen: boolean; openLeft() { this.isOpen = !this.isOpen; } To toggle classes ...

The labels on the viewcontroller take a considerable amount of time to load with

I am encountering a challenge with the slow loading of labels in my view controller. In this script, a userid is sent to a php script which then retrieves data related to that userid in an array. The data is sent back as a json response to the app. Howeve ...

Utilizing various filters and sorting options on API response within Angular 8

Upon receiving the following API response: [ { "imgPaths":[ "gallery/products/55ccb60cddb4d9bded02accb26827ce4" ], "_id":"5f3e961d65c6d591ba04f3d3", "productName":" ...

What is preventing me from assigning to a class variable within a $http success handler?

During the course of my project, I have encountered a perplexing situation that is difficult to comprehend. My intuition tells me that the issue lies in a peculiar nuance of javascript while I am working in TypeScript. Unfortunately, I am unable to prove t ...

Directive does not support the new animations in Angular 2 RC 4

It appears that in the current release, we are only able to add animations to components and cannot define them as directives. For example: The following code works: @Component({ selector: "animate-demo", animations: [ trigger('openC ...

Generating a JSON object using HTML select elements

Looking to generate a JSON string that includes select values and inner HTML values in a map format. For example: <select id="my-select"> <option value="1">one</option> <option value="2">two</option> </select> var json ...

Is it possible to have Angular and Node.JS Express running on the same port?

It seems like I may have a duplicated question, but I'm struggling to figure out how to properly configure and run the frontend and backend together. I've looked into solutions on this and this questions, but I'm still confused. Currently, ...

Extracting values from a JSON array

I am attempting to modify values within an array in a JSON object using sed and jq. The structure of the object is as follows: { "alertrulemethoddata": "", "alertruleimportance": 50, "alertruletype": "any& ...

angular locally implementing paging with a JSON file

I am currently in the process of setting up a service that will allow me to switch to live data from an API whenever I choose. The getData function includes skip and take parameters to specify the starting record and number of records to retrieve. At the ...

Determine the full path of a JSON object

So, I'm dealing with a JSON object that looks like this: { ""settings"": { ""general"": { ""database"": { ""type"": ""PostgreSql"" } } } } To determine the absolute path of this JSON object, it would be: settings/general/database/ ...

What is the best approach to managing exceptions consistently across all Angular 2/ Typescript observables?

Throughout the learning process of Angular2, I have noticed that exceptions are often caught right at the point of the call. For example: getHeroes(): Promise<Hero[]> { return this.http.get(this.heroesUrl) .toPromise() ...

Utilizing Generics in TypeScript to Expand Abstract Classes

How can I define the property eventList in the class ImplTestClass to be an array with all possible values of AllowedEvents, while extending the class TextClass that accepts T? I'm stuck on this one. If anyone can provide guidance on how to achieve t ...