Skip to content

Instantly share code, notes, and snippets.

@akinsho
Forked from kylealwyn/merge-deep.js
Created March 27, 2018 18:02
Show Gist options
  • Save akinsho/22f2629f61edcb9d6642df05f35ebe22 to your computer and use it in GitHub Desktop.
Save akinsho/22f2629f61edcb9d6642df05f35ebe22 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