Skip to content

Instantly share code, notes, and snippets.

@kerrishotts
Created October 4, 2014 21:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kerrishotts/12c86d2a57f8b5bc1aca to your computer and use it in GitHub Desktop.
Save kerrishotts/12c86d2a57f8b5bc1aca to your computer and use it in GitHub Desktop.
Object Merge
/**
* Merges the supplied objects together and returns a copy containin the merged objects. The original
* objects are untouched, and a new object is returned containing a relatively deep copy of each object.
*
* Important Notes:
* - Items that exist in any object but not in any other will be added to the target
* - Should more than one item exist in the set of objects with the same key, the following rules occur:
* - If both types are arrays, the result is a.concat(b)
* - If both types are objects, the result is merge(a,b)
* - Otherwise the result is b (b overwrites a)
* - Should more than one item exist in the set of objects with the same key, but differ in type, the
* second value overwrites the first.
* - This is not a true deep copy! Should any property be a reference to another object or array, the
* copied result may also be a reference (unless both the target and the source share the same item
* with the same type). In other words: DON'T USE THIS AS A DEEP COPY METHOD
*
* It's really meant to make this kind of work easy:
*
* var x = { a: 1, b: "hi", c: [1,2] },
* y = { a: 3, c: [3, 4], d: 0 },
* z = merge (x,y);
*
* z is now { a: 3, b: "hi", c: [1,2,3,4], d:0 }.
*
* License MIT. Copyright Kerri Shotts 2014
*/
function merge() {
"use strict";
var t = {},
args = Array.prototype.slice.call( arguments, 0 );
args.forEach( function ( s ) {
Object.keys( s )
.forEach( function ( prop ) {
var e = s[ prop ];
if ( e instanceof Array ) {
if ( t[ prop ] instanceof Array ) {
t[ prop ] = t[ prop ].concat( e );
} else if ( !( t[ prop ] instanceof Object ) || !( t[ prop ] instanceof Array ) ) {
t[ prop ] = e;
}
} else if ( e instanceof Object && t[ prop ] instanceof Object ) {
t[ prop ] = merge( t[ prop ], e );
} else {
t[ prop ] = e;
}
} );
} );
return t;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment