Last active
January 24, 2016 02:10
-
-
Save carlfriess/6cb55f98f3ee4dada47b to your computer and use it in GitHub Desktop.
Function to update javascript object with contents of another object
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 update(obj) { | |
for (var i=1; i<arguments.length; i++) { | |
for (var prop in arguments[i]) { | |
var val = arguments[i][prop]; | |
if (Object.prototype.toString.call(val) === '[object Array]') { //Array | |
obj[prop] = []; | |
update(obj[prop], val); | |
} | |
else if (typeof val == 'object' && !(val instanceof Date) && val != null) { //Object | |
if (typeof obj[prop] != 'object' || obj[prop] == null) { | |
obj[prop] = {}; | |
} | |
update(obj[prop], val); | |
} | |
else //Everything else | |
obj[prop] = val; | |
} | |
} | |
return obj; | |
} | |
// Minified: | |
// function update(t){for(var e=1;e<arguments.length;e++)for(var r in arguments[e]){var a=arguments[e][r];"[object Array]"===Object.prototype.toString.call(a)?(t[r]=[],update(t[r],a)):"object"!=typeof a||a instanceof Date||null==a?t[r]=a:(("object"!=typeof t[r]||null==t[r])&&(t[r]={}),update(t[r],a))}return t} | |
// Example: | |
// update({ "a": 1 , "b": 2 }, { "a": 4 , "c": 3 }) -> { "a": 4, "b": 2, "c": 3 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment