Skip to content

Instantly share code, notes, and snippets.

@evenicoulddoit
Created February 1, 2015 20:42
Show Gist options
  • Save evenicoulddoit/5b9188625d337cacb709 to your computer and use it in GitHub Desktop.
Save evenicoulddoit/5b9188625d337cacb709 to your computer and use it in GitHub Desktop.
JS Nested Merge
function merged() {
var mergeInto;
[].forEach.call(arguments, function(obj, i) {
if(i === 0) {
mergeInto = obj;
}
else {
Object.keys(obj).forEach(function(key) {
var existing = mergeInto[key],
value = obj[key];
if(!existing || value.constructor != existing.constructor ||
[Object, Array].indexOf(value.constructor) == -1) {
mergeInto[key] = value;
}
else {
if(value.constructor == Array) {
existing.push.apply(existing, value);
}
else {
mergeInto[key] = merged({}, existing, value);
}
}
});
}
});
return mergeInto;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment