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
?
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.
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.
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.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With