Created
January 30, 2020 13:09
-
-
Save neroze/ff393e45ca99b6add0faa69d1a1c0b04 to your computer and use it in GitHub Desktop.
deep merge
This file contains 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 object check. | |
* @param item | |
* @returns {boolean} | |
*/ | |
export function isObject(item) { | |
return item && typeof item === 'object' && !Array.isArray(item); | |
} | |
/** | |
* Deep merge two objects. | |
* @param target | |
* @param ...sources | |
*/ | |
export function mergeDeep(target, ...sources) { | |
if (!sources.length) return target; | |
const source = sources.shift(); | |
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 mergeDeep(target, ...sources); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment