Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript merging objects by id

What's the correct way to merge two arrays in Javascript?

I've got two arrays (for example):

var a1 = [{ id : 1, name : "test"}, { id : 2, name : "test2"}] var a2 = [{ id : 1, count : "1"}, {id : 2, count : "2"}] 

I want to be able to end up with something like:

var a3 = [{ id : 1, name : "test", count : "1"},            { id : 2, name : "test2", count : "2"}] 

Where the two arrays are being joined based on the 'id' field and extra data is simply being added.

I tried to use _.union to do this, but it simply overwrites the values from the second array into the first one

like image 797
Tam2 Avatar asked Oct 20 '13 16:10

Tam2


People also ask

Can we merge two objects in JavaScript?

To merge two objects in JavaScript, you can use the spread ... operator. The spread operator creates a new object with all the properties from the first and second object. If there's two properties with the same name, the property from the second object wins out.

How do you join two objects in JavaScript?

JavaScript Merge 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 do I combine two arrays of objects?

We can use the spread operator on arrays within an array literal( [] ) to merge them. Let's see it with an example. First, we will take two arrays, arr1 and arr2 . Then merge the arrays using the spread operator( ... ) within an array literal.


2 Answers

This should do the trick:

var mergedList = _.map(a1, function(item){     return _.extend(item, _.findWhere(a2, { id: item.id })); }); 

This assumes that the id of the second object in a1 should be 2 rather than "2"

like image 187
Gruff Bunny Avatar answered Sep 19 '22 20:09

Gruff Bunny


Short ES6 solution

const a3 = a1.map(t1 => ({...t1, ...a2.find(t2 => t2.id === t1.id)})) 
like image 35
Andreas Tzionis Avatar answered Sep 20 '22 20:09

Andreas Tzionis