FacundoGFlores FacundoGFlores - 1 month ago 17
TypeScript Question

Mapping backend's properties to frontend properties

Suppose we have the following result from backend:

{
idPerson:string,
name: string
}


Now I have a typescript class:

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


So, the backend is giving me the following:

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


when I receive the answer from an angular http request I am doing the following:

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


So it gives me:

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


But I really want to map the keys from backend to the frontend keys and obtain:

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


How can I map them?

Answer

let options: Option[];
options = JSON.parse(response).map(item => ({
  id: item.idPerson,
  text: item.name
}));

In the case you don't need any methods in the Option class I would create an interface instead.

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

let options: Option[];
options = JSON.parse(response).map(item => ({
  id: item.idPerson,
  text: item.name
}));

If you do need methods on the Option class though:

class Option {
  constructor(public id: string, public text: string) {}

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

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