Skip to content

Instantly share code, notes, and snippets.

@rxaviers
Last active December 24, 2015 02:59
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rxaviers/6734630 to your computer and use it in GitHub Desktop.
Save rxaviers/6734630 to your computer and use it in GitHub Desktop.
Merge javascript JSON's
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( "," ) + "}" );
};
@scarver2
Copy link

scarver2 commented Nov 3, 2013

Nice!

Implementation:

var json_result = merge(object1, object2);
=> {...json: data...}

@rxaviers
Copy link
Author

rxaviers commented Nov 4, 2013

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