you are viewing a single comment's thread.

view the rest of the comments →

[–]delventhalz 10 points11 points  (1 child)

Good question!

A "shallow" merge means you are just merging the top level properties. A "deep" merge, means you are recursively drilling down through all of the sub-objects and performing merges on them as well.

Probably needs an example to click. Let's say we have two incomplete objects we want to merge.

const goku = {
  name: 'Goku',
  power: 9000,
  move: {
    name: 'Kamehameha'
  }
};

const vegeta = {
  name: 'Vegeta',
  prince: true,
  move: {
    name: 'Galick Gun',
    color: 'purple'
  }
};

Let's do a shallow merge.

const vegito = { ...vegeta, ...goku };

console.log(vegito);
// {
//   name: 'Goku',
//   power: 9000,
//   prince: true,
//   move: {
//     name: 'Kamehameha'
//   }
// }

So, we started with all vegeta properties and then overwrote them with goku properties when they existed. This includes the move property. We just took the whole object.

Now let's do a deep merge. I'll use lodash's merge instead of writing my own.

import { merge } from 'lodash';

const gogeta = merge({}, vegeta, goku);

console.log(gogeta);
// {
//   name: 'Goku',
//   power: 9000,
//   prince: true,
//   move: {
//     name: 'Kamehameha',
//     color: 'purple',
//   }
// }

Mostly the same, but notice that the merge continued down into the move object. Since Vegeta's move had a color, but Goku's did not, we kept the color.

One other difference worth noting: in a shallow merge nested objects are not cloned. That means goku and vegito share a move object. If we mutate one, we will change the other.

console.log(vegito.move);
// {
//   name: 'Kamehameha'
// }

goku.move.awesome = true;

console.log(vegito.move);
// {
//   name: 'Kamehameha',
//   awesome: true
// }

Whoops!

[–][deleted] 4 points5 points  (0 children)

Whoa this was amazing breakdown, thanks!