Categories
JavaScript Answers

How to convert a JSON object to a JavaScript class instance?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *