What is the difference between deep and shallow merge of objects in javascript? As far as I understand, deep merge recursively copies all the source object enumerable properties into target object. But what does shallow merge do?
In a shallow merge, the properties of the first object are overwritten with the same property values of the second object.
To merge two objects in JavaScript, you can use the spread ... operator. The spread operator creates a new object with all the properties from the first and second object. If there's two properties with the same name, the property from the second object wins out.
Merges the enumerable properties of two or more objects deeply.
JavaScript Merge Objects To merge objects into a new one that has all properties of the merged objects, you have two options: Use a spread operator ( ... ) Use the Object. assign() method.
In a shallow merge, the properties of the first object are overwritten with the same property values of the second object.
Lets look at an example. Setup:
var obj1 = { foo: { prop1: 42, }, }; var obj2 = { foo: { prop2: 21, }, bar: { prop3: 10, }, };
Shallow:
var result = { foo: { // `foo` got overwritten with the value of `obj2` prop2: 21, }, bar: { prop3: 10, }, };
Deep:
var result = { foo: { prop1: 42, prop2: 21, // `obj2.foo` got merged into `obj1.foo`. }, bar: { prop3: 10, }, };
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With