Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
164
rated 0 times [  170] [ 6]  / answers: 1 / hits: 31657  / 6 Years ago, thu, september 13, 2018, 12:00:00

I have a http request that gets this Json object from a nosql database:



let jsonBody = {
birthday : 1997,
firstname: 'foo',
lastname:'bar'
}


Then I want to load this information into the Student model:



class Student{
constructor(){

}

getFullname(){
return this.lastname+' '+this.firstname
}
getApproxAge(){
return 2018- this.birthday
}
}


Normally, I would add this method to this class:



fromJson(json){
this.studentId = json.studentId;
this.birthday = json.birthday;
this.firstname = json.firstname;
this.lastname = json.lastname;
}


I would use it as follow:



let student = new Student()
student.fromJson(jsonBody)
console.log(student.getFullname())
console.log(student.getApproxAge())


This works fine but my problem is I have: 100 proprieties in reality. Will I have to write all proprities one by one in the fromJson method?



And also, if a propriety name has change, let's say: lastname became LastName, I will have to fix it?



Is there a simpler way to just assign these values to the object student dynamically but keep all of its methods??



Something like this:



fromJson(json){
this = Object.assign(this, json) //THIS IS NOT WORKING
}

More From » class

 Answers
-3

Just assign to an instance:



 static from(json){
return Object.assign(new Student(), json);
}


So you can do:



 const student = Student.from({ name: whatever });





Or make it an instance method and leave away the assignemnt:



 applyData(json) {
Object.assign(this, json);
}


So you can:



 const student = new Student;
student.applyData({ name: whatever });


It could also be part of the constructor:



 constructor(options = {}) {
Object.assign(this, options);
}


Then you could do:



 const student = new Student({ name: whatever });



And also, if a property name has changed, let's say: lastname became LastName, I will have to fix it?




Yes you will have to fix that.


[#53502] Monday, September 10, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
raveno

Total Points: 453
Total Questions: 92
Total Answers: 92

Location: France
Member since Thu, Oct 27, 2022
2 Years ago
raveno questions
;