javascript 如何将 JSON 数据映射到类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30339675/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 12:04:26  来源:igfitidea点击:

How to map JSON data to a class

javascriptecmascript-6babeljs

提问by Nigiri

I created a ES6 class by Babeland I want to map JSON data which is gotten from a server to the ES6 class.
Is there anything common way to do that?

我通过Babel创建了一个 ES6 类,我想将从服务器获取的 JSON 数据映射到 ES6 类。
有没有什么通用的方法可以做到这一点?

User.js

用户.js

export default class User {
  constructor() {
    this.firstName;
    this.lastName;
    this.sex;
  }
}

app.js

应用程序.js

import User from "./classes/User";

var data = JSON.parse(req.responseText);
console.log(data.firstname); //Bob
//now...just set data one by one?

回答by

I would merge the JSON object into thisusing Object.assign, as follows:

我会将 JSON 对象合并到thisusing 中Object.assign,如下所示:

class User {
  firstName;
  lastName;
  sex;

  constructor(data) {
    Object.assign(this, data);
//  ^^^^^^^^^^^^^^^^^^^^^^^^^^
  }
}

var data = JSON.parse(req.responseText);
new User(data);