Merging objects without overwriting existing values

Viewed 20

I have 2 objects that look like this.

Object 1

{ 
  value1: true,
  support: [{
      id: 5,
      ghi: 600
    },{
      id: 8,
      ghi: 900
  }], 
  value3: "any"
}

and then I have this Object 2

support: [{
   id: 5
},{
   id: 8
},{ 
   id: 12
}]

The expected output should be only the ID's in Object 2 but keeping the ghi value if it exists:

   { 
      value1: true,
      support: [{
          id: 5,
          ghi: 600
        },{
          id: 8,
          ghi: 900
        },{
          id: 12,
      }], 
      value3: "any"
   }

How can I merge object 2 into Object 1 without overwriting any existing support.id's? I was using the spread operator until I found bugs in my code caused by the overwriting/removal of ghi on merge

...(object1 ?? {}), ...object2

I don't want it to overwrite existing ones because then it removes the ghi value. How can I make it check for the ID first?

Thanks

1 Answers

Instead of merging obj1 in obj2, merge obj2 in obj1

const { ...object2, ...object1 }
Related