Created
December 8, 2016 21:15
-
-
Save kylealwyn/75d9045ea2c5e8d4a1b983005cfaf198 to your computer and use it in GitHub Desktop.
recursively merge two javascript objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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