打字稿:将 json 从 api 调用转换为 Array<object>

Dav*_*vid 5 typescript angular

从 API,我收到下一个 json:

[{
  "id: "0",
  "name_surname": "John Smith",
  "age": 33,
  "profile__image": "..."
},{
  "id: "1",
  "name_surname": "Juan García",
  "age": 32,
  "profile__image": "..."
}]
Run Code Online (Sandbox Code Playgroud)

我在打字稿中有下一节课:

export class Employee {
    public Id: string = null;
    public NameSurname: string = null;
    public Age: number = 0;
    public ProfileImage: string = null;
}
Run Code Online (Sandbox Code Playgroud)

我想作为Array<Employee>api 调用的结果返回。

正如您在 api 调用中看到的那样,我收到了由下划线 (_) 分隔的属性的数组。如何在没有下划线的情况下转换为标准类?

谢谢

pc_*_*der 3

演示将构造函数添加到您的 Employee 模型

 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
        }

    }
Run Code Online (Sandbox Code Playgroud)

然后将组件映射数据结果添加到您的模型中

result:Employee[];

this.result=this.data.map(x=>  new Employee(x));
Run Code Online (Sandbox Code Playgroud)

Demo2如果您不想使用构造函数,那么您可以在模型中定义函数。

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以打电话

this.result=this.data.map(x=>  new Employee().mapObj(x));
Run Code Online (Sandbox Code Playgroud)