Skip to content

Instantly share code, notes, and snippets.

@ithinkandicode
Last active August 19, 2019 20:51
Show Gist options
  • Save ithinkandicode/474b5fbcfd5725803ee24dbe68af6c03 to your computer and use it in GitHub Desktop.
Save ithinkandicode/474b5fbcfd5725803ee24dbe68af6c03 to your computer and use it in GitHub Desktop.
JS – Deep Merge Test
/**
* Deep merge test
*
* Performs a recursive Object.assign, copying properties from source to target
* without removing any of the targets own properties
*
* @param {object} target Target object, to copy properties to
* @param {object} source Source object, to copy proeprties from
*
* @return {objuect} Merged object
*/
function deepMerge(target, source)
{
// Start with a clone of the target object
// (copy target props to empty obj, then set the new merged var to that obj)
let merged = Object.assign({}, target);
// Loop through the properties of the source object,
// to compare these props against the target's props
for(const prop in source)
{
// Is property exclusive to source?
if (!target.hasOwnProperty(prop))
{
// Exclusive source property: We can copy this over directly
merged[prop] = source[prop];
}
else
{
// Shared property: Is it an object (so do we need to iterate over it?)
if (typeof source[prop] !== 'object')
{
// Not an object, no iteration necessary, safe to copy!
merged[prop] = source[prop];
}
else
{
// Shared property is an object, so iterate over its own properties
// This starts the whole loop over again, at a deeper property level
Object.assign(merged[prop], deepMerge(merged[prop], source[prop]));
}
}
}
return merged;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment