Home > Back-end >  typescript how to assign class to json object array
typescript how to assign class to json object array

Time:07-02

Let say if I have a array of JSON object, how to cast or assign the class (Report class) to it?

console.log('jsonBody '   jsonBody);
//print jsonBody [object Object],[object Object]

console.log('jsonBody '   JSON.stringify(jsonBody));
//print jsonBody [{"created_at":"2016-02-04","updated_at":"2016-02-04 00:45:56.000"}, {"created_at":"2016-02-04","updated_at":"2016-02-04 00:45:56.000"}]

//typescript class
export class Report {
  created_at!: Date;
  updated_at!: Date;
}

CodePudding user response:

Create a constructor that accepts an object of the json type:

class Report {
  created_at!: Date;
  updated_at!: Date;
  
  constructor({created_at, updated_at}: {created_at: string, updated_at: string}) {
      this.created_at = new Date(created_at);
      this.updated_at = new Date(updated_at);
  }
}

let jsonBody = [{"created_at":"2016-02-04","updated_at":"2016-02-04 00:45:56.000"}, {"created_at":"2016-02-04","updated_at":"2016-02-04 00:45:56.000"}];

let arr: Report[] = jsonBody.map(obj => new Report(obj));
  • Related