Connecting the attributes of the backend to the corresponding attributes on the frontend

If we receive the following data from the backend:

{
    idPerson:string, 
    name: string
}

Let's say I have a TypeScript class like this:

class Option {
    id: string;
    text: string;
}

Now, suppose the backend sends us this data:

"[{idperson: "1", name: "foo"}, {idperson:"2", name:"bar"}]"

When I make an Angular HTTP request and get the response, I'm parsing it like this:

let options: any[] = [];
options = JSON.parse(response);

So far, the output looks like:

[{idperson: "1", name: "foo"}, {idperson:"2", name:"bar"}]

But what I really want is to map the keys from backend to frontend keys to achieve this format:

[{id: "1", text: "foo"}, {id:"2", text:"bar"}]

Is there a way for me to do this key mapping?

Answer №1

let data: Data[];
data = JSON.parse(response).map(item => ({
  id: item.idNumber,
  value: item.name
}));

If you find that you don't require any specific methods within the Data class, I recommend creating an interface instead.

interface Data {
  id: string;
  value: string;
}

let data: Data[];
data = JSON.parse(response).map(item => ({
  id: item.idNumber,
  value: item.name
}));

However, if you do need to include methods in the Data class:

class Data {
  constructor(public id: string, public value: string) {}

  public performAction() {
    console.log(this.id)
  }
}

let options: Option[];
options = JSON.parse(response).map(item => new Data(item.idNumber, item.name));

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

Issue encountered while attempting to initiate a new project with Angular CLI

Encountering an error while trying to create a new app using Angular CLI Attempted solutions: npm cache clean --force npm cache verify Unfortunately, the above steps did not resolve the issue Please refer to the image linked below https://i.sstatic.ne ...

Steps for generating a unit test for code that invokes scrollIntoView on an HTML element

I'm currently working on an Angular component where I have a method that involves scrolling through a list of elements known as "cards" based on certain criteria. Despite my efforts to write unit tests for this method using the Jasmine framework, I&ap ...

Error 404 Encountered During Azure Functions GET Request

I have double-checked the file and everything seems to be correct. The name matches the Azure website, the API Key is included, but I am not getting any response when trying to use this on Postman as a GET request. What could be the issue? //https://disn ...

Translation of title in Ionic 3 action sheet

In my Ionic 3 Angular app, I am using the Action Sheet and Ngx Translate plugin. However, when it comes to translating the action sheet title, I have encountered an issue. Normally, in other parts of my app, specifying the translation like below works fin ...

What is the best way to compile TypeScript files without them being dependent on each other?

I have created a TypeScript class file with the following code: class SampleClass { public load(): void { console.log('loaded'); } } Now, I also have another TypeScript file which contains functions that need to utilize this class: // ...

Angular 2: Creating a Reusable Object for Uniform JSON Structures

I am facing an issue with JSON data as I have 3 tables in my database named "dictionary" with the same structure but different column names: {"id":1,"test_1":"test"},{"id":2,"test_1":"lalala"} - first JSON {"id":1,"test_2":"****"},{"id":2,"test_2":"afe ...

The art of accurately encoding/decoding a Duration field in Flutter using JSON

I've encountered an error while using the convert package for a specific task. The code snippet in question includes a factory method called Brick.fromJson and a function named createBrick that makes a POST request to an API endpoint. factory Brick.fr ...

Typescript: Verifying if a parameter matches a specific type

Here are my constructor implementations: constructor(position: FlagPosition, flag: string); constructor(position: FlagPosition, flag: Expression<any> | string) { this.position = position; //TODO: Check if flag type is a string or an Expressi ...

Applying a setvalidator to a FormControl doesn't automatically mark the form as invalid

HTML code <div> <label for="" >No additional information flag:</label> <rca-checkbox formControlName="noAdditionalInfoCheckbox" (checkboxChecked)="onCheckboxChecked($event)"></rca-chec ...

Do Angular 2 component getters get reevaluated with each update?

What advantages do getters offer compared to attributes initialized using ngOnInit? ...

Is there a way to pass a JSON variable as a parameter in an Alamofire POST request?

When utilizing Alamofire to send a post request, I encountered an issue with the following code snippet: Alamofire.request("https://test.com", method: .post, parameters: d, encoding: JSONEncoding.default) .responseJSON { response in print(resp ...

What is the syntax for creating a link tag with interpolation in Angular 2 / Ionic 2?

As I work on developing an app using Ionic 2/Angular 2, I have encountered a challenge that I am struggling to overcome. Let me provide some context: I am retrieving multiple strings from a webservice, and some of these strings contain links. Here is an e ...

How can I retrieve data from MongoDB using the default data type?

Currently, I am in the process of setting up a new server with Node.js connecting to MongoDB using Mongoose. However, I have encountered an issue where when I use model.find(), it returns data but not in the default JSON type expected from MongoDB. User.f ...

The content of the external json file needs to be allocated to corresponding html divs with matching names

As I am new to jQuery and JavaScript, I am on the search for a method to incorporate data from an external JSON file into HTML code. The data objects in JSON have the same names as their corresponding HTML divs. This should also occur during the onLoad eve ...

What are the steps to deactivate all formal controls?

I have developed a comprehensive form that resembles the one below: ... export function directoryForm( countries: CountryModel[], dealers: DealerModel[], translate: TranslateService ): FormlyFieldConfig[] { return [ { type: 'stepper ...

Using a basic XML file in Angular: A beginner's guide

Incorporating XML into my Angular app is a necessity. While the most straightforward approach would be to store it as a string, like so: xml = '<?xml version="1.0" encoding="UTF-8"?>\n' + '<note>\n ...

TypeScript Generics: Property types do not match (the properties listed are missing)

In the code snippet below, I've defined an interface, type, and a function. interface ActionWithGeneric<T> { type: 'add' | 'remove'; data: T; } type StateWithGeneric<T> = Array<ActionWithGeneric<T>> ...

Import divX from page2 into page 1 by utilizing jsonp to circumvent the restrictions of the same origin policy

I've been attempting to load a div from another page with the following code, $('#result').load('page2.php #divX') However, the JavaScript on that page doesn't seem to work, even though both page1 and page2 are linked to the ...

Exploring and interpreting JSON data

Looking to create a script to extract specific GameServers stats using the JSON method. Specifically interested in only retrieving the hostname field. How can this be achieved? JSON [ [ { "ip": "176.57.188.22", "port" ...

Retrieve parent form validation within a child component Angular 5 control value accessor

I found helpful information on this website: My goal is to implement validation for all fields in a child component using control value accessor and template driven forms. (For reference, here is the link to the issues on Stackblitz: https://stackblitz.c ...