DEV Community

Cover image for Merging Deep Object Literals In JavaScript
Brian Gaines
Brian Gaines

Posted on

Merging Deep Object Literals In JavaScript

I was looking to merge a couple of deep Object Literals (only one level deep for both objects) but then had a brain fart and realized that I cannot simply merge them like we may think using the spread operator {...obj1, ...obj2 } as this only supports a single level of the object.

const obj1 = {
  test: {
    a: 1,
    b: 1
  }
}

const obj2 = {
  test: {
    b: 2,
    c: 3
  }
}

const bad_merge = {
  ...obj1,
  ...obj2
}

console.log(bad_merge);


// 🔴 Results -- Whoops, Looks like the 2nd object replaced the 1st object, hmmm…
{
  test: {
    b: 2,
    c: 3
  }
}

Enter fullscreen mode Exit fullscreen mode

Since we know that we have only a single level deep, we can restructure our merge like we have below; however, this is a fairly simple modification, but if you have objects you need to merge that have a various set of nested levels, then you may want to reach for lodash.merge


const good_merge = {
  test: {
    ...obj1.test,
    ...obj2.test
  }
}

// ✅ expected. That’s better…
{
  test: {
    a: 1,
    b: 2,
    c: 3
  }
}

Enter fullscreen mode Exit fullscreen mode

Hope this helps you the next time you’re needing to merge some objects. Welcome any comments or issues you had with merging objects together.

Happy Coding!
Brian

Top comments (0)