Reputation: 3639
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?
Upvotes: 24
Views: 23364
Reputation: 342
you can use this npm package https://www.npmjs.com/package/class-converter to map all JSON to a class. it looks like following one:
import { property, toClass } from 'class-convert';
class UserModel {
@property('i')
id: number;
@property()
name: string;
}
const userRaw = {
i: 1234,
name: 'name',
};
// use toClass to convert plain object to class
const userModel = toClass(userRaw, UserModel);
// you will get a class, just like below one
{
id: 1234,
name: 'name',
}
Upvotes: 0
Reputation:
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);
Upvotes: 39