Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two objects with ES6 [duplicate]

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?

like image 815
Tom Oakley Avatar asked Aug 24 '16 11:08

Tom Oakley


People also ask

How do I merge objects in ES6?

The easiest way to merge two objects in JavaScript is with the ES6 spread syntax / operator ( ... ). All you have to do is insert one object into another object along with the spread syntax and any object you use the spread syntax on will be merged into the parent object.

How do you combine two objects?

To merge objects into a new one that has all properties of the merged objects, you have two options: Use a spread operator ( ... ) Use the Object. assign() method.

How can I merge properties of two JavaScript objects dynamically?

The two most common ways of doing this are: Using the spread operator ( ... ) Using the Object. assign() method.


1 Answers

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 );
like image 121
Ori Drori Avatar answered Sep 22 '22 21:09

Ori Drori