Sometimes, we want to convert a JSON object to a JavaScript class instance.
In this article, we’ll look at how to convert a JSON object to a JavaScript class instance.
How to convert a JSON object to a JavaScript class instance?
To convert a JSON object to a JavaScript class instance, we can merge the content of the JSON object into this in the constructor.
For instance, we write:
class Student {
constructor(json) {
Object.assign(this, json);
}
}
const student = new Student({
firstName: "jane"
});
console.log(student)
to define the Student class.
In the constructor, we call Object.assign with this and json to merge the json into this.
Then we create a new Student instance and return it.
Therefore, student is {firstName: 'jane'}.
Conclusion
To convert a JSON object to a JavaScript class instance, we can merge the content of the JSON object into this in the constructor.