If you want to map objects to something (in this case a property). I think Array.prototype.map is what you're looking for if you want to code functionally.

(fiddle)

If you want to support older browsers, that are not ES5 compliant you can shim it (there is a polyfill on the MDN page above). Another alternative would be to use underscorejs's pluck method:

var users = [
      {name: "Joe", age: 22},
      {name: "Kevin", age: 24},
      {name: "Peter", age: 21}
    ];
var result = _.pluck(users,'name').join(",")
Answer from Benjamin Gruenbaum on Stack Overflow
🌐
TutorialsPoint
tutorialspoint.com › join-two-objects-by-key-in-javascript
Join two objects by key in JavaScript
November 23, 2020 - We are required to write a JavaScript function that takes in these two arrays. And our function should merge the child array objects into corresponding parent objects.
Discussions

Combine json arrays by key, javascript - Stack Overflow
This is a fine answer, demonstrating ... exactly that. Nor among the answers to the questions Merge two array of objects based on a key or How can I perform an inner join with two object arrays in JavaScript?.... More on stackoverflow.com
🌐 stackoverflow.com
November 7, 2017
javascript - Merge two array of objects based on a key - Stack Overflow
It does not "join" on arr1.id == arr2.id as OP has asked. 2018-10-08T04:08:08.093Z+00:00 ... Title is “Merge two array of objects based on a key”. OP also mentions in post “based on id”. 2018-10-09T09:31:41.653Z+00:00 ... This does not respect a key / key-value. It just merge every item from array. The question was: How to merge two arrays by ... More on stackoverflow.com
🌐 stackoverflow.com
Joining multiple objects by a key in javascript - Stack Overflow
“Does the idea that Jesus could ... form of belief in reincarnation?” · Pf2e - How does Overwhelming Combination and Reap the Field interact ... Where in the kernel is my "Failed to setup vendor infoframe on connector HDMI-A-2: -22" dmesg coming from? ... Would you accept authorship on a largely AI-generated scientific software paper if you only joined at the validation stage? Can an Artificer cast V, S, or V/S spells as M only? Output a one column query as a JSON array of ... More on stackoverflow.com
🌐 stackoverflow.com
javascript - join array of objects by using one property - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
🌐
Codemzy
codemzy.com › blog › array-join-object-property
Using Array join() on an object property - Codemzy's Blog
May 30, 2023 - You can use Array.join() on an array of objects, but `join()` will only work with strings, so you need to get the property value(s) first. Let's look at some examples.
🌐
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 - Then, you can use Array.prototype.reduce() to combine them based on the specified key. 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 ...
🌐
EyeHunts
tutorial.eyehunts.com › home › javascript merge an array of objects by key | example code
JavaScript merge an array of objects by key | Example code
September 15, 2022 - <!DOCTYPE html> <html> <body> <script> let arr1 = [ { id: "abc1", date: "2017-01-24" }, { id: "abc2", date: "2017-01-22" } ]; let arr2 = [ { id: "abc3", name: "John" }, { id: "abc4", name: "Tim" } ]; let arr3 = arr1.map((item, i) => Object.assign({}, item, arr2[i])); console.log(arr3); </script> </body> </html> ... 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); ... let merged = []; for(let i=0; i<arr1.length; i++) { merged.push({ ...arr1[i], ...arr2[i] }); } console.log(merged); ... Do comment if you have any doubts or suggestions on this JS Merge array code.
🌐
GitHub
github.com › urbanairship › join-by-keys
GitHub - urbanairship/join-by-keys: Join an array of objects on a common key or keys. · GitHub
Create a new object representing the join of the matching elements by doing the iterating over each key and applying the following rules: If key is in keys, on the new object, set the key to the value of the first matching object.
Author: urbanairship
Find elsewhere
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);
Run code snippetEdit code snippet Hide Results Copy to answer Expand


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);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

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);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

2 of 16
80

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 code snippetEdit code snippet Hide Results Copy to answer Expand

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"
  }
]
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › join
Array.prototype.join() - JavaScript - MDN Web Docs
4 days ago - When an array is cyclic (it contains an element that is itself), browsers avoid infinite recursion by ignoring the cyclic reference. ... When used on sparse arrays, the join() method iterates empty slots as if they have the value undefined. The join() method is generic. It only expects the this value to have a length property and integer-keyed properties.
🌐
Stack Overflow
stackoverflow.com › questions › 43443411 › joining-multiple-objects-by-a-key-in-javascript
Joining multiple objects by a key in javascript - Stack Overflow
6 For Array, is it more efficient to use map() & reduce() instead of forEach() in javascript? 1 Join 2 arrays in object with repeated keys · 22 Joining property values of objects in an array · 3 How to join object values without a loop? 1 How do you join items in array based upon their key?
🌐
EyeHunts
tutorial.eyehunts.com › home › javascript join the array of objects | example code
JavaScript join the array of objects | Example code
August 19, 2022 - In modern JavaScript, this will ... "Peter", age: 21} ].map(e => e.name).join(",")); ... A simple example code uses the .join() method to get a single string, with each element separated by commas, like so:...
🌐
npm
npmjs.com › package › array-join
array-join - npm
March 11, 2026 - Join two iterables (e.g. arrays) of objects by a common (user-defined) key, similarly to how SQL JOIN, LEFT JOIN and FULL JOIN work.
      » npm install array-join
    
Published: Mar 11, 2026
Version: 4.0.0
Top answer
1 of 3
4

Like this?

var combined = [];
function findSecond(id,second){
    for (var i=0;i<second.length;i++){
        if(second[i].id === id){
            return second[i];
        }
    }
    return null
}

while (el = arr1.pop()){
    var getSec = findSecond(el.id,arr2);
    if (getSec){
        for (var l in getSec){
            if (!(l in el)) {
                el[l] = getSec[l];
            }
        }
        combined.push(el);
    }
}

If the arrays have the same length, and the id's are equal, a simpler merge will do:

function merge(a1,a2) {
    var i = -1;
    while ((i = i+1)<a1.length)  {
     for (var l in a2[i]) {
            if (!(l in a1[i] )) {
                a1[i][l] = a2[i][l];
            }
     }
    }
   return a1; 
}

Here's a working example

[Edit 2016/07/30] Added a snippet using more functional approach and, based on @djangos comment, an extra method to combine both arrays.

Show code snippet

(function() {
    var alert = function(str) {document.querySelector('#result').textContent += str + '\n';};
    var arrays = getArrays();
  
    alert('Combine on id (shared id\'s):')
    alert(JSON.stringify(combineById(arrays.arr1, arrays.arr2), null, ' '));
  
    alert('\nCombine on id (all id\'s):')
    alert(JSON.stringify(combineBothById(arrays.arr1, arrays.arr2), null, ' '));
  
    // for combineBothById the parameter order isn't relevant
    alert('\nCombine on id (all id\'s, demo parameter order not relevant):')
    alert(JSON.stringify(combineBothById(arrays.arr2, arrays.arr1), null, ' '));
  
    // combine first array with second on common id's
    function combineById(arr1, arr2) {
      return arr1.map(
          function (el) {
                var findInB = this.filter(function (x) {return x.id === el.id;});
                if (findInB.length) {
                    var current = findInB[0];
                    for (var l in current) {
                        if (!el[l]) {el[l] = current[l];}
                    }
                }
                return el;
          }, arr2);
    }

    // combine first array with second on all id's
    function combineBothById(arr1, arr2) {
        var combined = arr1.map(
            function (el) {
                var findInB = this.filter(function (x) {return x.id === el.id;});
                if (findInB.length) {
                    var current = findInB[0];
                    for (var l in current) {
                        if (!el[l]) {el[l] = current[l];}
                    }
                }
                return el;
            }, arr2);
        combined = combined.concat(arr2.filter(
            function (el) {
                return !this.filter(function (x) {return x.id === el.id;}).length;
            }, combined));
        return combined;
    }
  
    function getArrays() {
        return {
            arr1: [{
                id: 1,
                name: 'fred',
                title: 'boss'
            }, {
                id: 2,
                name: 'jim',
                title: 'nobody'
            }, {
                id: 3,
                name: 'bob',
                title: 'dancer'
            }],
            arr2: [{
                id: 1,
                wage: '300',
                rate: 'day'
            }, {
                id: 2,
                wage: '10',
                rate: 'hour'
            }, {
                id: 4,
                wage: '500',
                rate: 'week'
            }]
        };
    }
}());
<pre id="result"></pre>
Run code snippetEdit code snippet Hide Results Copy to answer Expand

2 of 3
2

You can merge two arrays by id column with Alasql library:

var res = alasql('SELECT * FROM ? arr1 JOIN ? arr2 USING id', [arr1,arr2]);

Try this example at jsFiddle.

🌐
W3Schools
w3schools.com › jsref › jsref_join.asp
JavaScript Array join() Method
The join() method does not change the original array. Any separator can be specified. The default is comma (,). ... Coding fundamentals as bite-sized lessons and challenges. ... If you want to use W3Schools services as an educational institution, ...
🌐
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.
🌐
GitHub
gist.github.com › sebysr › 6acada64a4b9d7ab21752ce6b81a8675
[Javascript] Merge objects with same key in array · GitHub
[Javascript] Merge objects with same key in array. GitHub Gist: instantly share code, notes, and snippets.