Wednesday, June 5, 2024
38
rated 0 times [  40] [ 2]  / answers: 1 / hits: 20689  / 9 Years ago, wed, may 20, 2015, 12:00:00

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?

More From » ecmascript-6

 Answers
4

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);

[#66533] Monday, May 18, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
donaldcristianl

Total Points: 114
Total Questions: 95
Total Answers: 110

Location: Bonaire
Member since Sat, May 27, 2023
1 Year ago
;