Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge two array of objects based on a key

Tags:

javascript

I have two arrays:

Array 1:

[   { id: "abdc4051", date: "2017-01-24" },    { id: "abdc4052", date: "2017-01-22" } ] 

and array 2:

[   { id: "abdc4051", name: "ab" },   { id: "abdc4052", name: "abc" } ] 

I need to merge these two arrays based on id and get this:

[   { id: "abdc4051", date: "2017-01-24", name: "ab" },   { id: "abdc4052", date: "2017-01-22", name: "abc" } ] 

How can I do this without iterating trough Object.keys?

like image 991
Adel Avatar asked Oct 20 '17 12:10

Adel


People also ask

How do I merge 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.

How do you combine two values of 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.

Can we combine two arrays in C?

To merge any two array in C programming, start adding each and every element of the first array to the third array (target array). Then start appending each and every element of the second array to the third array (target array) as shown in the program given below.


1 Answers

You can do it like this -

let arr1 = [      { id: "abdc4051", date: "2017-01-24" },      { id: "abdc4052", date: "2017-01-22" }  ];    let arr2 = [      { id: "abdc4051", name: "ab" },      { id: "abdc4052", name: "abc" }  ];    let arr3 = arr1.map((item, i) => Object.assign({}, item, arr2[i]));    console.log(arr3);

Use below code if arr1 and arr2 are in a different order:

let arr1 = [    { id: "abdc4051", date: "2017-01-24" },     { id: "abdc4052", date: "2017-01-22" }  ];    let arr2 = [    { id: "abdc4051", name: "ab" },    { id: "abdc4052", name: "abc" }  ];    let merged = [];    for(let i=0; i<arr1.length; i++) {    merged.push({     ...arr1[i],      ...(arr2.find((itmInner) => itmInner.id === arr1[i].id))}    );  }    console.log(merged);

Use this if arr1 and arr2 are in a same order

let arr1 = [    { id: "abdc4051", date: "2017-01-24" },     { id: "abdc4052", date: "2017-01-22" }  ];    let arr2 = [    { id: "abdc4051", name: "ab" },    { id: "abdc4052", name: "abc" }  ];    let merged = [];    for(let i=0; i<arr1.length; i++) {    merged.push({     ...arr1[i],      ...arr2[i]    });  }    console.log(merged);
like image 139
Rajaprabhu Aravindasamy Avatar answered Sep 20 '22 14:09

Rajaprabhu Aravindasamy