Last active
February 10, 2019 21:29
-
-
Save metavoid/774dbdf7196e133777bde80d1290bb8f to your computer and use it in GitHub Desktop.
Deep merge JS objects (unlike shallow merge of Object.assign and else)
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
| //Recursive deep merge JS objects (unlike shallow merge of Object.assign and else) | |
| function deepMerge(target, source) { | |
| let output = Object.assign({}, target); | |
| if (this.isObject(target) && this.isObject(source)) { | |
| Object.keys(source).forEach(key => { | |
| if (this.isObject(source[key])) { | |
| if (!(key in target)) | |
| Object.assign(output, { | |
| [key]: source[key] | |
| }); | |
| else output[key] = this.deepMerge(target[key], source[key]); | |
| } else { | |
| Object.assign(output, { | |
| [key]: source[key] | |
| }); | |
| } | |
| }); | |
| } | |
| return output; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment