Skip to content
Advertisement

Having an issue with Javascript spread

Consider the two objects:

obj1

{
   myObj: {
      key1: "value1",
      key2: "value2"
   }
}

obj2

{
   myObj: {
      key2: "new_value2",
      key3: "value3",
   }
}

I’m trying to do the following:

let combined = {...obj1, ...obj2};

The intended output is:

{
   myObj: {
      key1: "value1",
      key2: "new_value2",
      key3: "value3"
   }
}

However, what I’m getting is:

{
   myObj: {
      key2: "new_value2",
      key3: "value3"
   }
}

It’s essentially overwriting obj1, not merging them.

How do I merge and overwrite?

Thanks!

Advertisement

Answer

You’ll have to use spread operator like below.

let combined = {myObj: {...obj1.myObj, ...obj2.myObj}}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement