0

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;
}
0

1 Answer 1

1

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));
Sign up to request clarification or add additional context in comments.

1 Comment

Or maybe make the constructor take two Date instances, and do the casting of strings in a separate Report.fromJSON helper function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.