Skip to content

Instantly share code, notes, and snippets.

@kylealwyn
Created December 8, 2016 21:15
Show Gist options
  • Save kylealwyn/75d9045ea2c5e8d4a1b983005cfaf198 to your computer and use it in GitHub Desktop.
Save kylealwyn/75d9045ea2c5e8d4a1b983005cfaf198 to your computer and use it in GitHub Desktop.
recursively merge two javascript objects
/**
* Simple is object check.
* @param item
* @returns {boolean}
*/
function isObject(item) {
return (item && typeof item === 'object' && !Array.isArray(item));
}
/**
* Deep merge two objects.
* @param target
* @param source
*/
function mergeDeep(target, source) {
if (isObject(target) && isObject(source)) {
for (const key in source) {
if (isObject(source[key])) {
if (!target[key]) Object.assign(target, { [key]: {} });
mergeDeep(target[key], source[key]);
} else {
Object.assign(target, { [key]: source[key] });
}
}
}
return target;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment