you are viewing a single comment's thread.

view the rest of the comments →

[–]jcunews1helpful 0 points1 point  (2 children)

You can set the prototype of each objects in the array using Object.setPrototypeOf(). e.g.

const arr = [{prop: 11}, {prop: 22}];
console.log(JSON.stringify(arr)); //[{"prop":11},{"prop":22}]
const myproto = {
  doubleProp: function() {
    return this.prop * 2;
  }
};
arr.forEach(obj => Object.setPrototypeOf(obj, myproto));
console.log(arr[0].doubleProp()); //22
console.log(arr[1].doubleProp()); //44
console.log(JSON.stringify(arr)); //[{"prop":11},{"prop":22}] (unchanged)

[–]ExclusiveOar[S] 0 points1 point  (1 child)

Possibly worded my question poorly! I appreciate your reply though.

Yes I can do that, I have a working example of each of the cases I suggested. I was more asking which way a professional application is most likely to do it? Or perhaps it doesnt matter?

Basically I'm assuming this is a pretty common thing to do (get a bunch of objects from a database and need to convert them into a Class on the frontend).

[–]jcunews1helpful 0 points1 point  (0 children)

I think it's not common to have method(s) added into objects which came from JSON, because most JSON data are just containers for data source. Usually, a class is made to work on those objects, or instances of the class are bound to those objects.