How to convert a JavaScript plain object into model class instance?

Sometimes, we want to convert a JavaScript plain object into model class instance.

In this article, we’ll look at how to convert a JavaScript plain object into model class instance.

How to convert a JavaScript plain object into model class instance?

To convert a JavaScript plain object into model class instance, we can use the Object.assign method.

For instance, we write:

class Model {
  constructor(obj) {
    Object.assign(this, obj)
  }
  print() {
    console.log(this.a);
  }
}

const obj = {
  a: 'a',
  b: 'b',
  c: 'c'
}
const m = new Model(obj)
console.log(m)
m.print()

to call Object.assign with this and obj in the Model class constructor.

This will merge the contents of obj into this.

Next, we instantiate a Model instance with obj.

And then we call m.print to print the content of this.a, which is 'a'.

Conclusion

To convert a JavaScript plain object into model class instance, we can use the Object.assign method.