Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deep and shallow merge in javascript

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?

like image 332
anand Avatar asked Mar 11 '17 04:03

anand


People also ask

What is shallow merge in JS?

In a shallow merge, the properties of the first object are overwritten with the same property values of the second object.

Can we merge two objects in JavaScript?

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.

What is JavaScript Deepmerge?

Merges the enumerable properties of two or more objects deeply.

How do you join two objects in JavaScript?

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.


1 Answers

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,   }, }; 
like image 117
Felix Kling Avatar answered Oct 21 '22 19:10

Felix Kling