120

I'm sure this question has been asked before but I can't quite find the answer I'm looking for, so here goes:

I have two objects, as follows:

const response = {
  lat: -51.3303,
  lng: 0.39440
}

let item = {
  id: 'qwenhee-9763ae-lenfya',
  address: '14-22 Elder St, London, E1 6BT, UK'
}

I need to merge these together to form this:

item = {
  id: 'qwenhee-9763ae-lenfya',
  address: '14-22 Elder St, London, E1 6BT, UK',
  location: {
    lat: -51.3303,
    lng: 0.39440
  }
}

I know I could do it like this:

item.location = {}
item.location.lat = response.lat
item.location.lng = response.lng

However, I feel that this is not the best way to do it anymore, because ES6 introduced the cool destructuring/assignment stuff; I tried deep object merging but it's unfortunately not supported :( I also looked through some ramda functions but couldn't see anything that was applicable.

So what is the best way to merge these two objects using ES6?

Tom Oakley
  • 6,065
  • 11
  • 44
  • 73
  • 1
    *"ES6 introduced the cool destructuring/assignment stuff"* Which doesn't help at all with merging object properties. – Felix Kling Aug 24 '16 at 14:03

2 Answers2

181

You can use Object.assign() to merge them into a new object:

const response = {
  lat: -51.3303,
  lng: 0.39440
}

const item = {
  id: 'qwenhee-9763ae-lenfya',
  address: '14-22 Elder St, London, E1 6BT, UK'
}

const newItem = Object.assign({}, item, { location: response });

console.log(newItem );

You can also use object spread, which is a Stage 4 proposal for ECMAScript:

const response = {
  lat: -51.3303,
  lng: 0.39440
}

const item = {
  id: 'qwenhee-9763ae-lenfya',
  address: '14-22 Elder St, London, E1 6BT, UK'
}

const newItem = { ...item, location: response }; // or { ...response } if you want to clone response as well

console.log(newItem );
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • 21
    Be careful if you do `const newItem = { ...item, location: response };`, because `location` property of `newItem` is a reference to `response` object. You'd better do it like `const newItem = { ...item, location: {...response} };` to avoid referencing and be safe. – hswner May 27 '18 at 11:05
  • `Object.assign` works for me.. thanks. – Hugo Leonardo Jul 09 '21 at 11:27
73

Another aproach is:

let result = { ...item, location : { ...response } }

But Object spread isn't yet standardized.

May also be helpful: https://stackoverflow.com/a/32926019/5341953

notgiorgi
  • 1,691
  • 12
  • 27
  • 5
    In this way, response saved as a pointer rather than a deep clone. This should be the correct answer `let result = { ...item, location : {...response} }` – FisNaN Mar 07 '18 at 13:15