Last active
October 5, 2017 12:08
-
-
Save mazhar266/c9ba906002f1c74ba67d to your computer and use it in GitHub Desktop.
Merge more than one JSON objects into one object in Node.JS
This file contains hidden or 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
/** | |
* @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