Are there any existing methods to append an object to another object?
I’ve had a quick stab at throwing this together but I’m not sure about a couple of things:
-
Am I handling methods correctly? I added an exception for append but what about when other prototype functions exist? Should I just ignore functions in the new class?
-
What should I do about null / undefined values?
-
Also, I’ve just thought about arrays.. what would be the best way to handle arrays? typeof reports as ‘object’.. I guess that testing the Array().constructor value would be the way forward
Other than these couple of issues it seems to function as I want it to (overwriting/adding individual parts of the existing object only where it exists in the new object). Are there any edge cases I’ve missed?
Object.prototype.append = function(_newObj)
{
if('object' !== typeof _newObj) {
console.info("ERROR!\nObject.prototype.append = function(_newObj)\n\n_newObj is not an Object!");
}
for (newVar in _newObj)
{
switch(typeof _newObj[newVar]){
case "string":
//Fall-through
case "boolean":
//Fall-through
case "number":
this[newVar] = _newObj[newVar];
break;
case "object":
this[newVar] = this[newVar] || {};
this[newVar].append(_newObj[newVar]);
break;
case "function":
if(newVar !== 'append'){
this[newVar] = _newObj[newVar];
}
break;
}
}
return this;
}
var foo = { 1:'a', 2:'b', 3:'c' };
var bar = { z: 26, y: 25, x: 24, w: { 'foo':'bar'}, v: function(){ alert('Hello world"'); } };
foo.append(bar);
console.info(foo);
I like it. I’ve used a similar, but not as robust method in my code. But it would probably be safer to implement it as a static method for the Object class:
To answer your questions, I haven’t found any better methods (outside of a framework) to do this either. For null/undefined values, you if the
_newObjhas null/undefined values, then shouldn’t your recipient object also have those (i.e. don’t make any special case for those)?