Skip to content

Instantly share code, notes, and snippets.

@gregnb
Created February 8, 2018 02:43
Show Gist options
  • Select an option

  • Save gregnb/57bfae310d1898112aade123fd7349ff to your computer and use it in GitHub Desktop.

Select an option

Save gregnb/57bfae310d1898112aade123fd7349ff to your computer and use it in GitHub Desktop.
deep merge two objects
// 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