Skip to content

Instantly share code, notes, and snippets.

@mazhar266
Last active October 5, 2017 12:08
Show Gist options
  • Save mazhar266/c9ba906002f1c74ba67d to your computer and use it in GitHub Desktop.
Save mazhar266/c9ba906002f1c74ba67d to your computer and use it in GitHub Desktop.
Merge more than one JSON objects into one object in Node.JS
/**
* @name merge
* @author Mazhar Ahmed
*
* this function will merge more than one json objects into one object
*
* @uses
* var object3 = merge(object1, object2);
*
*/
var merge = function() {
var destination = {};
var sources = [].slice.call(arguments, 0);
sources.forEach(function(source) {
var prop;
for (prop in source) {
if (prop in destination && Array.isArray(destination[prop])) {
// Concat Arrays
destination[prop] = destination[prop].concat(source[prop]);
} else if (prop in destination && typeof destination[prop] === 'object') {
// Merge Objects
destination[prop] = merge(destination[prop], source[prop]);
} else {
// Set new values
destination[prop] = source[prop];
}
} // end of for
}); // end of forEach
return destination;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment