Skip to content

Instantly share code, notes, and snippets.

@carlfriess
Last active January 24, 2016 02:10
Show Gist options
  • Save carlfriess/6cb55f98f3ee4dada47b to your computer and use it in GitHub Desktop.
Save carlfriess/6cb55f98f3ee4dada47b to your computer and use it in GitHub Desktop.
Function to update javascript object with contents of another object
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