Paolo Benvenuto
Paolo Benvenuto

Reputation: 417

convert an object to a class instance

I have a javascript app that reads a json file on the server; the function that reads the json file returns an object.

Until now I was using that object (it represents an album of photos) in the app, but now I want to make it an instance of a class, so that I'm going to manipulate it through the class methods.

Surely I'm doing something like:

var album = new Album(object);

My question is: what is the best way to generate the class properties in the constructor? can I iterate on the object properties with something like:

Object.keys(object).forEach(function(key) {
  this[key] = object.key;
}

or should I assign manually each object property to the corresponding class property?

Upvotes: 0

Views: 347

Answers (1)

imvain2
imvain2

Reputation: 15857

In this case, I'm going to say best is a matter of opinion. What you are doing will work and is clean and simple but it should fail due to this and the function reference also due to the missing ).

The following version should work for you.

Object.keys(object).forEach((key) => {
  this[key] = object[key];
})

Upvotes: 1

Related Questions