A
A
Anton V.2020-11-20 21:19:49
JavaScript
Anton V., 2020-11-20 21:19:49

How to optimally create instances of a class taking data in json?

Good afternoon!

Comes from the server in json format 1000 objects with 10 properties each.
Then each object must be inherited from a certain class, so that there would be the necessary methods for working with the entity.

Here, for example, is such an option, but I would not like to allocate memory again, create new objects, copy literals.

class MaterialItem {
id
title
...

constructor(item) {
  for(let name in item)
     this[name] = item[name];
}

/** methods */
}


What are the best options in terms of performance?

Thank you!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton V., 2020-11-26
@ivinnic

Found this way.

json_data.forEach(item=>{
  Object.setPrototypeOf(item, ItemClass.prototype)
})

Already better than forit all the properties.
Are there any pitfalls?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question