打字稿如何将类分配给JSON对象数组

发布于 2025-02-12 04:16:29 字数 436 浏览 1 评论 0原文

假设我有JSON对象的数组,如何将类或分配给它?

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

画尸师 2025-02-19 04:16:29

创建一个接受JSON类型对象的构造函数:

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));

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));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文