如何将JSON数据映射到类 [英] How to map JSON data to a class
本文介绍了如何将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);
这篇关于如何将JSON数据映射到类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文