Created
February 8, 2018 02:43
-
-
Save gregnb/57bfae310d1898112aade123fd7349ff to your computer and use it in GitHub Desktop.
deep merge two 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
| // mergeDeep({ a: {b: 2} }, { a: { b: 5 }}) | |
| // = { a: { b: 5 }} | |
| function mergeDeep(obj1, obj2) { | |
| let newObj = { ...obj2 }; | |
| const recurseObj = (obj1, obj2) => { | |
| Object.keys(obj1).forEach(key => { | |
| if (typeof obj1[key] === "object" && obj2[key] !== undefined) { | |
| recurseObj(obj1[key], obj2[key]); | |
| } else if (obj2[key] === undefined) { | |
| obj2[key] = obj1[key]; | |
| } | |
| }); | |
| }; | |
| recurseObj(obj1, newObj); | |
| return newObj; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment