How to map JSON data to a class

点点圈 提交于 2019-12-20 11:56:09

问题


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

User.js

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

app.js

import User from "./classes/User";

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

回答1:


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

class User {
  firstName;
  lastName;
  sex;

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

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


来源:https://stackoverflow.com/questions/30339675/how-to-map-json-data-to-a-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!