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);
You forgot "boolean" as in
typeof true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With