33

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?

anand
  • 351
  • 1
  • 3
  • 6
  • 3
    Possible duplicate of [What is the difference between a deep copy and a shallow copy?](http://stackoverflow.com/questions/184710/what-is-the-difference-between-a-deep-copy-and-a-shallow-copy) – Melissa Mar 11 '17 at 04:50
  • 5
    @FirstOrGoat: Copying and merging are two different things. – Felix Kling Mar 11 '17 at 04:53

1 Answers1

62

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,
  },
};
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 4
    Is it that shallow merge just checks the first level properties in the object to merge? say for example , we have var obj1 = { foo: { prop1: 42, foosInnerObj: { someProp: someVal } }, }; Does shallow merge ignore 'foosInnerObj' completely? and keeps only prop2 from obj2 in foo? – anand Mar 11 '17 at 05:08
  • 1
    Yep. It's basically just `obj1.foo = obj2.foo;` (assuming you merge into `obj1`). Hence the term "shallow". – Felix Kling Mar 11 '17 at 05:12
  • Thanks felix, It helped :) – anand Mar 11 '17 at 05:13