-4

I have 2 objects that I want merge together

Object1 = {'1234':{name: 'One'},'4567': {name: 'two'}}
Object2 = {'1234':{id: 1234, location: 'paris'},'4567':{id: 4567, location: 'london'}}

If the id match the object key , merge it it.

I want a result like this:

Object3 = {'1234':{id: 1234, name: 'One', location: 'paris'},'4567':{id: 4567, name: 'two', location: 'london'}}

If I try spread operator or Object.assign , it overwrite the previous object.

1 Answers1

-1

You most likely want to iterate through one of the objects and merge each value.

const Object1 = {'1234':{name: 'One'},'4567': {name: 'two'}};
const Object2 = {'1234':{id: 1234, location: 'paris'},'4567':{id: 4567, location: 'london'}};
const Object3 = {};

for (let key in Object1) {
    Object3[key] = {...Object2[key], ...Object1[key]}
}

console.log(Object3);

Additionally you can add some if statements to check whether or not key exist in both objects.

tomsidorov
  • 26
  • 1
  • 3