Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
82
rated 0 times [  89] [ 7]  / answers: 1 / hits: 43936  / 11 Years ago, tue, may 7, 2013, 12:00:00

I want to add multiple attributes to an existing object with existing attributes. Is there a more concise way than one line per new attribute?



myObject.name = 'don';
myObject.gender = 'male';


Everything on MDN shows how to do new objects with bracket notation, but not existing objects: https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Working_with_Objects


More From » oop

 Answers
8

From How can I merge properties of two JavaScript objects dynamically?



var obj2 = {name: 'don', gender: 'male'};
for (var attrname in myobject) { myobject[attrname] = obj2[attrname]; }


EDIT



To be a bit clearer about how you could extend Object to use this function:



//Extend the protype so you can make calls on the instance
Object.prototype.merge = function(obj2) {
for (var attrname in obj2) {
this[attrname] = obj2[attrname];
}
//Returning this is optional and certainly up to your implementation.
//It allows for nice method chaining.
return this;
};
//Append to the object constructor function so you can only make static calls
Object.merge2 = function(obj1, obj2) {
for (var attrname in obj2) {
obj1[attrname] = obj2[attrname];
}
//Returning obj1 is optional and certainly up to your implementation
return obj1;
};


Usage:



var myObject1 = { One: One };
myObject1.merge({ Two: Two }).merge({ Three: Three });
//myObject1 is { One: One, Two: Two, Three: Three, merge: function }


var myObject2 = Object.merge2({ One: One }, { Two: Two });
Object.merge2(myObject2, { Three: Three });
//myObject2 is { One: One, Two: Two, Three: Three }


Note: You certainly could implement a flexible merge conflict strategy depending on your needs.


[#78377] Monday, May 6, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dontaemauricioc

Total Points: 456
Total Questions: 84
Total Answers: 99

Location: Puerto Rico
Member since Fri, Oct 14, 2022
2 Years ago
;