I’m currently using a pseudo object structure in my javascript. For example:
MyObj = function(options) {
options = options || {};
this.valueA = options.valueA || 'A';
this.valueB = options.valueB || 'B';
this.valueC = options.valueC || 'C';
this.valueD = options.valueD || 'D';
}
MyObj.prototype.doStuff() {
// do stuff
}
Now I need to update an instance of the above, based on JSON data that only contains the attributes that have changed.
Currently I’m using a function kinda like:
MyObj.prototype.update(obj) {
if(obj.valueA) this.valueA = obj.valueA;
if(obj.valueA) this.valueB = obj.valueB;
if(obj.valueA) this.valueC = obj.valueC;
if(obj.valueA) this.valueD = obj.valueD;
}
Now in the above example it all all works fine, however some of my defined objects are quite large and some of the attributes are not simple (in that a if(x) is not adequate). This makes the code both messy and complex. The complexity IMHO is that I’m forced to maintain two separate places when I introduce new attributes. This concerns me as I’m aware how this can be a cause of introduced defects.
So my question is thus, is there a javascript mechanism that I can use to apply the attributes of an object to my instance of ‘MyObj’? I’m not happy with my approach and I’m finding it difficult to search for questions on this subject (suspect this is due to my lack of knowledge on the correct javascript terms for these entities).
Btw, the obj is created from parsing JSON data.
Are you looking for some sort of merge mechanism?
Could this work for you?