Skip to content

Instantly share code, notes, and snippets.

@ycmjason
Created January 28, 2018 22:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ycmjason/477c71fa424edbfb5c255aa5e97924ef to your computer and use it in GitHub Desktop.
Save ycmjason/477c71fa424edbfb5c255aa5e97924ef to your computer and use it in GitHub Desktop.
Deep version of Object.assign.
const objectAssignDeep = (...objs) => objs.reduce((acc, obj) => Object.assign(acc, ...Object.keys(obj).map(key => {
if (acc[key] instanceof Object && obj[key] instanceof Object) {
return { [key]: objectAssignDeep({}, acc[key], obj[key]) };
}
return { [key]: obj[key] };
})));
@ycmjason
Copy link
Author

ycmjason commented Jan 28, 2018

Example:

objectAssignDeep({}, {a: {b: 3, c:5}}, {a: {c: 6, d:7}}) // { a: { b: 3, c: 6, d: 7 } }

Note that this function has the same characteristic as Object.assign, the first object will be mutated and the rest remains.

obj1 = {};
obj2 = {a: {b: 3, c:5}};
obj3 = {a: {c: {}, d:7}};
objectAssignDeep(obj1, obj2, obj3); // { a: { b: 3, c: {}, d: 7 } }

obj1; // { a: { b: 3, c: {}, d: 7 } }
// obj2, obj3 unchanged

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment