I have a class defined in Javascript with some members and methods. I also have a JSON object that has the same member variables as my class but, obviously, not the methods. What is the easiest way to convert my JSON object to an instance of the class?
Below some code that explains better my case. I've tried to use Object.assign without success. Can this be done in a one liner?
function Thing(a, b){
this.a = a;
this.b = b;
this.sum = function(){ return this.a + this.b; };
this.printSum = function(){ console.log (this.sum()); };
};
// test it works
z = new Thing(4,3);
z.printSum(); // shows 7
// attempt with Object.assign
y = JSON.parse('{"a": 5, "b": 4}'); // initialize y from JSON object
console.log(y);
Object.assign(y, new Thing()); // trying to copy methods of Thing into y
console.log(y); // shows both a and b undefined (assign overwrited also a and b)
y.printSum(); // shows NaN
// trying Object.assing the other way around
y = JSON.parse('{"a": 5, "b": 4}');
Object.assign(new Thing(), y); // trying the other way around
console.log(y); // methods from thing are not present now
y.printSum(); // gives error y.printSum is not a function (obvious, as it is not present)
classsyntax you don't needObject.assign. You can use the constructor toconstructyour instance!