Created
August 15, 2012 21:55
-
-
Save joseanpg/3364036 to your computer and use it in GitHub Desktop.
Extend and Merge (don't overwrite properties that reference objects)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(carrier){ | |
var hasOwn = Object.prototype.hasOwnProperty; | |
var slice = Array.prototype.slice; | |
function extend(obj,src){ | |
for (var p in src){ | |
if (hasOwn.call(src,p)) { | |
if (p in obj && typeof obj[p] === 'object' && obj[p]) { | |
extend(obj[p],src[p]); | |
} | |
else { | |
obj[p] = src[p]; | |
} | |
} | |
} | |
} | |
function merge(){ | |
var result = {}; | |
var args = slice.call(arguments,0); | |
for (var i=0, len=args.length;i<len;i++){ | |
extend(result,args[i]); | |
} | |
return result; | |
} | |
carrier.extend = extend; | |
carrier.merge = merge; | |
})(this); | |
/* | |
var a = {}; | |
var b = {a:'Hello', b:{}}; | |
var c = {a:'Bye', b:{f:{d:2}}, c:1}; | |
var r = merge(a, b, c); | |
alert(JSON.stringify(r,null,0)); //{"a":"Bye","b":{"f":{"d":2}},"c":1} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You are right :)