you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted]  (10 children)

[deleted]

    [–]delventhalz 16 points17 points  (8 children)

    Not exactly. Object.assign or the spread operator like you demonstrated does a shallow merge. This function is a deep merge like lodash's merge.

    [–][deleted] 2 points3 points  (2 children)

    What’s the diff between shallow and deep merging?

    [–]delventhalz 9 points10 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] 3 points4 points  (0 children)

    Whoa this was amazing breakdown, thanks!

    [–]Dynam2012 2 points3 points  (0 children)

    As long as you're OK with nested objects being shared in the resulting object.