Typescript: Converting json from api call to Array<object>

Viewed 356

From API, I am receiving next json:

[{
  "id: "0",
  "name_surname": "John Smith",
  "age": 33,
  "profile__image": "..."
},{
  "id: "1",
  "name_surname": "Juan García",
  "age": 32,
  "profile__image": "..."
}]

I have the next class in typescript:

export class Employee {
    public Id: string = null;
    public NameSurname: string = null;
    public Age: number = 0;
    public ProfileImage: string = null;
}

I want to return as Array<Employee> the result of api call.

As you see in the api call I receive the array with the properties separated by underscore (_). How can I convert to standard class without underscore?

Thx

2 Answers

Demo add constructor to your Employee model

 export class Employee {
        public Id: string = null;
        public NameSurname: string = null;
        public Age: number = 0;
        public ProfileImage: string = null;

        constructor(param:any){
          this.Id=param.id;
          this.NameSurname=param.name_surname,
          this.Age=param.age,
          this.ProfileImage=param.profile__image
        }

    }

then in component map data result to your model

result:Employee[];

this.result=this.data.map(x=>  new Employee(x));

Demo2 if you dont want use constructor then then you can define function inside your model.

export class Employee {
    public Id: string = null;
    public NameSurname: string = null;
    public Age: number = 0;
    public ProfileImage: string = null;
    
    constructor(){ }

    mapObj(param:any){
      this.Id=param.id;
      this.NameSurname=param.name_surname,
      this.Age=param.age,
      this.ProfileImage=param.profile__image
      return this;
    }
}

then you can call like

this.result=this.data.map(x=>  new Employee().mapObj(x));
import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {

  data = [{
    id: '0',
    name_surname: 'John Smith',
    age: 33,
    profile__image: '...'
  }, {
    id: '1',
    name_surname: 'Juan García',
    age: 32,
    profile__image: '...'
  }];

  myArray: Array<Employee>;

  convertData () {
    this.data.forEach(element => {
      this.myArray.push({
        Id: element.id,
        NameSurname: element.name_surname,
        Age: element.age,
        ProfileImage: element.profile__image
      });
    });
  }
}

export class Employee {
  public Id: string = null;
  public NameSurname: string = null;
  public Age: number = 0;
  public ProfileImage: string = null;
}
Related