如何将JSON数据映射到类
问题描述:
我通过 Babel 创建了一个ES6课程,我想要映射从服务器获取的JSON数据到ES6课程。
有什么常见的方法吗?
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?
答
我会将JSON对象合并到此
使用 Object.assign
,如下所示:
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);