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);

Answer from Rajaprabhu Aravindasamy on Stack Overflow
Top answer
1 of 16
137

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);

2 of 16
81

This solution is applicable even when the merged arrays have different sizes. Also, even if the matching keys have different names.

Merge the two arrays by using a Map as follows:

const arr1 = [
  { id: "abdc4051", date: "2017-01-24" }, 
  { id: "abdc4052", date: "2017-01-22" },
  { id: "abdc4053", date: "2017-01-22" }
];
const arr2 = [
  { nameId: "abdc4051", name: "ab" },
  { nameId: "abdc4052", name: "abc" }
];

const map = new Map();
arr1.forEach(item => map.set(item.id, item));
arr2.forEach(item => map.set(item.nameId, {...map.get(item.nameId), ...item}));
const mergedArr = Array.from(map.values());

console.log(JSON.stringify(mergedArr));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Run the stack snippet to see the result:

[
  {
    "id": "abdc4051",
    "date": "2017-01-24",
    "nameId": "abdc4051",
    "name": "ab"
  },
  {
    "id": "abdc4052",
    "date": "2017-01-22",
    "nameId": "abdc4052",
    "name": "abc"
  },
  {
    "id": "abdc4053",
    "date": "2017-01-22"
  }
]
🌐
30 Seconds of Code
30secondsofcode.org › home › javascript › array › combine object arrays
Combine 2 JavaScript object arrays based on a key - 30 seconds of code
March 26, 2024 - For each value in the arrays, you can check if the object has the specified key. If it does, you can add it to the accumulator object, combining it with any existing object that has the same key.
🌐
30 Seconds of Code
30secondsofcode.org › home › javascript › object › merge objects
Merge two or more JavaScript objects - 30 seconds of code
March 20, 2024 - const obj1 = { a: 1, b: 2 }; const ... their values. This can be done by checking if the key already exists in the resulting object and appending the value to an array if it does....
🌐
Paige Niedringhaus
paigeniedringhaus.com › merge javascript objects in an array with different defined properties
Merge JavaScript Objects in an Array with Different Defined Properties | Paige Niedringhaus
June 6, 2022 - This mergeObject() function is the one that actually does the combining of objects. The A and B objects that this function takes in are the two objects with a common sensorId property, and the res variable will be the newly returned object of their properties (and values) combined.
🌐
DEV Community
dev.to › pmbanugo › how-to-merge-two-array-of-string-into-a-keyvalue-pair-object-in-javascript-2pp1
How To Merge Two Array of String Into A Key/Value Pair (Object) In JavaScript - DEV Community
June 8, 2023 - We're going to create a function that takes in two arguments: one for the array of keys, and the other for the values. That function will use the reduce() method to produce an object of key/value pair.
🌐
Reactgo
reactgo.com › javascript-merge-array-objects-key
JavaScript merge array of objects by key (es6) | Reactgo
July 24, 2023 - function mergeArrayObjects(arr1,arr2){ let start = 0; let merge = []; while(start < arr1.length){ if(arr1[start].id === arr2[start].id){ //pushing the merged objects into array merge.push({...arr1[start],...arr2[start]}) } //incrementing start value start = start+1 } return merge; } ... How to exit the JavaScript functionHistory of JavaScriptHow to combine two arrays in JavaScriptHow to convert String to Date in JavaScriptHow to Solve date.getDay is not a Function in JavaScriptHow to get number of keys in JavaScript object
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › merge-javascript-objects-with-the-same-key-value-and-count-them
Merge JavaScript objects with the same key value and count them
We are required to write a JavaScript function that takes in one such array. The function should then merge all those objects together that have the common value for "id" property.
🌐
SitePoint
sitepoint.com › blog › javascript › how to merge objects in javascript
How to Merge Objects in JavaScript — SitePoint
November 5, 2024 - The spread operator (...) is a common approach to merge objects in JavaScript. It has the form {...object1, ...object2}. When properties with the same keys exist in the source objects, the spread operator overwrites the values in the target ...
🌐
Dirask
dirask.com › posts › JavaScript-merge-objects-in-array-with-the-same-keys-DKgNRD
JavaScript - merge objects in array with the same keys
// ONLINE-RUNNER:browser; const array = [ { type: 1, values: 'a' }, { type: 1, values: ['b', 'c'] }, { type: 2, values: 'd' } ]; const result = []; array.forEach((object) => { const existing = result.filter((item) => item.type == object.type); if (existing.length) { const existingIndex = result.indexOf(existing[0]); result[existingIndex].values = result[existingIndex].values.concat(object.values); } else { if (typeof object.values == 'string') object.values = [object.values]; result.push(object); } }); console.log(JSON.stringify(result)); ... If you want values to be an array of numbers instead of strings, just change the condition in line 15 from 'string' to 'number' type. JavaScript - group / grouping array items with reduce method
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-merge-two-different-arrays-of-objects-with-unique-values-only-in-javascript
How to Merge two Different Arrays of Objects with Unique Values in JavaScript? | GeeksforGeeks
July 5, 2024 - Adding duplicate object keys with ... the same key from multiple objects in an array, creating a new object where each key corresponds to an array of associated values. Table of Content Using for...of LoopUsi ... Typically, in JavaScript, combining two objects is a commonplace thing to do, but when it involves intricate nesting, deep merging turns out ...
🌐
Medium
isaacpro01.medium.com › merging-two-arrays-of-objects-based-on-object-keys-in-javascript-96bd215dd3b3
Merging two arrays of objects based on object keys in Javascript | by Isaac Ssemugenyi | Medium
June 15, 2021 - It might seem like alot of reputation but we need to construct another array from the joinedDetails array we created before, and in the new array at Line 5 we iterate through all objects in the array returning the name, age and for country_name we filter out all elements in the arrays (which was a value to the country_id in the joinedDetails array) with an empty string, then return only the element at index 0 which for this case will be the actual required country_name. Now our finalUserDetails would look something like:- ... The full implementation is in this code below. Hope you enjoyed reading. Some other implementation that can be worth you exploration can be found here. ... Software Engineer with Stanbic Flyhub Uganda, Love programming with javascript, nodejs, vuejs, react, react-native and Java.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › how-to-merge-multiple-array-of-object-by-id-in-javascript
How to Merge Multiple Array of Object by ID in JavaScript? - ...
August 23, 2024 - For each object, the find method is used on the second array to locate a corresponding object by ID. Object.assign then creates a new object by combining the properties of the original object and the matched object, resulting in a merged array.
🌐
GitHub
gist.github.com › sebysr › 6acada64a4b9d7ab21752ce6b81a8675
[Javascript] Merge objects with same key in array · GitHub
[Javascript] Merge objects with same key in array · Raw · MergeObjectIntoArray.js · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
Reddit
reddit.com › r/learnjavascript › best way to merge two objects on a matching key-value pair.
r/learnjavascript on Reddit: Best way to merge two objects on a matching key-value pair.
September 15, 2021 -

Hey,

I'm having trouble making two objects into one on a matching key.

I have two objects coming from 2 apis and there is one matching key in the objects.

I want to iterate over them and if the storeId matches in both objects, I want to merge the two together as seen in the perfectObject.

I have tried the spread operator, Object.assign, for...in loop instead of the for loop seen here, but found close to none success.

Thanks for the help!

const logistics = [
{
"logisticsId": "L5E69E26D8FCAE",
"storeId": 409388,
"logisticsDate": "2020-03-12T07:19:09.000Z"
},]

const stores = [
{
"storeId": 409388,
"ka": 0,
"country": "ru",
"name": "test",
"city": "Moscow",
"cxw": 1,
"cx": 1,
"plz": 22448
}]

const perfetObject = {

"storeId": 409388,
"ka": 0,
"country": "ru",
"name": "test",
"city": "Moscow",
"cxw": 1,
"cx": 1,
"plz": 22448,

"logisticsId": "L5E69E26D8FCAE",
"storeId": 409388,
"logisticsDate": "2020-03-12T07:19:09.000Z"

}

let d = {}

for(let i = 0; i < logistics.length; ++i) {
for (let k = 0; k < stores.length; ++k) {
if(logistics.storeId === stores.storeId) {
d = {
...stores .name,
...stores .city,
...logistics.logisticsId
}
}
}
}

console.log(d)

🌐
YouTube
youtube.com › watch
JavaScript : Merge two array of objects based on a key
Enjoy the videos and music you love, upload original content, and share it all with friends, family, and the world on YouTube.
🌐
Quora
quora.com › How-do-you-merge-two-objects-and-sum-the-values-of-the-same-key-in-JavaScript
How to merge two objects and sum the values of the same key in JavaScript - Quora
Answer: There is usually more than one way to solve a problem in programming. I’m assuming you’re asking this because of a practice problem you encountered either at school or during your own self-learning journey, so instead of simply writing some code for you and leaving it at that, let’s ...