Last active
December 24, 2015 02:59
-
-
Save rxaviers/6734630 to your computer and use it in GitHub Desktop.
Merge javascript JSON's
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
function merge() { | |
var i, json, | |
jsons = []; | |
for ( i = 0; i < arguments.length; i++ ) { | |
json = JSON.stringify( arguments[ i ] ).replace( /^{/, "" ).replace( /}$/, "" ); | |
if ( json ) { | |
jsons.push( json ); | |
} | |
} | |
return JSON.parse( "{" + jsons.join( "," ) + "}" ); | |
}; |
Nice!
Implementation:
var json_result = merge(object1, object2);
=> {...json: data...}
Note the above merge function doesn't handle deep elements. Eg:
merge( { a: { b: 1, c: 2 } }, { a: { b: 3, d: 4 } } )
=> { a: { b: 3, d: 4 } }
If you need a deep merge. Eg:
merge( { a: { b: 1, c: 2 } }, { a: { b: 3, d: 4 } } )
=> { a: { b: 3, c: 2, d: 4 } }
Consider using this instead: http://jsfiddle.net/amTEH/ (http://stackoverflow.com/questions/14974864/combine-or-merge-json-on-node-js-without-jquery/14974931#comment28268748_14974931)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Did you like? Please, vote up http://stackoverflow.com/questions/14974864/combine-or-merge-json-on-node-js-without-jquery#comment28171654_14979212