Created
December 7, 2019 02:09
-
-
Save vensauro/184b37d784c10449c38d3a7112c82bf8 to your computer and use it in GitHub Desktop.
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
| /** | |
| * Performs a deep merge of `source` into `target`. | |
| * Mutates `target` only but not its objects and arrays. | |
| * | |
| * @author inspired by [jhildenbiddle](https://stackoverflow.com/a/48218209). | |
| */ | |
| function mergeDeep(target, source) { | |
| const isObject = (obj) => obj && typeof obj === 'object'; | |
| if (!isObject(target) || !isObject(source)) { | |
| return source; | |
| } | |
| Object.keys(source).forEach(key => { | |
| const targetValue = target[key]; | |
| const sourceValue = source[key]; | |
| if (Array.isArray(targetValue) && Array.isArray(sourceValue)) { | |
| target[key] = targetValue.concat(sourceValue); | |
| } else if (isObject(targetValue) && isObject(sourceValue)) { | |
| target[key] = mergeDeep(Object.assign({}, targetValue), sourceValue); | |
| } else { | |
| target[key] = sourceValue; | |
| } | |
| }); | |
| return target; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment