Here is one option:-

var array = [{
  name: "foo1",
  value: "val1"
}, {
  name: "foo1",
  value: ["val2", "val3"]
}, {
  name: "foo2",
  value: "val4"
}];

var output = [];

array.forEach(function(item) {
  var existing = output.filter(function(v, i) {
    return v.name == item.name;
  });
  if (existing.length) {
    var existingIndex = output.indexOf(existing[0]);
    output[existingIndex].value = output[existingIndex].value.concat(item.value);
  } else {
    if (typeof item.value == 'string')
      item.value = [item.value];
    output.push(item);
  }
});

console.dir(output);

Answer from BenG on Stack Overflow
🌐
EyeHunts
tutorial.eyehunts.com › home › merge javascript objects in array with same key es6 | example code
Merge JavaScript objects in array with same key es6 | Example code
September 16, 2022 - <!DOCTYPE html> <html> <head> <script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script> </head> <body> <script> const listOfQuestions = [{ question1: { important: true } }, { question2: { important: false } }]; const listOfAnswers = [{ question1: { answer: false } }, { question2: { answer: true } }]; const result = _.merge(listOfQuestions, listOfAnswers) console.log(result) </script> </body> </html> ... var arr = [ { "abc": [ { "name": "test", "addr": "123", } ] }, { "def": [ { "first_name": "test", "last_name": "test" } ] }, { "def": [ { "first_name": "test1", "last_name": "test1" } ] }] const result = arr.reduce((acc, curr) => { const key = Object.keys(curr)[0] const found = acc.find(i => i[key]) if (!found) { acc.push(curr) } else { found[key] = [ ...found[key], ...curr[key] ] } return acc; }, []) console.log(result)
Discussions

javascript - Merge two array of objects based on a key - Stack Overflow
Your solution will only work if ... in the same order, with relation to the id property ofc. In the real world, it isn't as simple as that. 2024-09-12T21:15:08.943Z+00:00 ... Save this answer. ... Show activity on this post. This is a version when you have an object and an array and you want to merge them and give the array a key value so it ... More on stackoverflow.com
🌐 stackoverflow.com
JavaScript merge array objects with the same keys - Stack Overflow
I tried to run the script as a ... get the same error. Any suggestions? 2022-04-13T01:21:30.58Z+00:00 ... function mergeData(data) { const acc = {} data.forEach(x => { const id = x.QuestionId if (!acc[id]) acc[id] = x else acc[id].myData = acc[id].myData.concat(x.myData) }) return Object.values(acc) } ... You can use forEach to create an object where the keys are the question IDs and then use Object.values to get the values into an array... More on stackoverflow.com
🌐 stackoverflow.com
javascript - how to merge objects in array with same key? - Stack Overflow
72 Merge JavaScript objects in array with same key More on stackoverflow.com
🌐 stackoverflow.com
javascript - Merging objects from array with the same key value - 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
🌐
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.
🌐
Dirask
dirask.com › posts › JavaScript-merge-objects-in-array-with-the-same-keys-DKgNRD
❤ 💻 JavaScript - merge objects in array with the same keys - Dirask
// 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
🌐
TutorialsPoint
tutorialspoint.com › article › merge-javascript-objects-with-the-same-key-value-and-count-them
Merge JavaScript objects with the same key value and count them
const arr = [{ "value": 10, "id": "111", "name": "BlackCat", }, { "value": 10, "id": "111", "name": "BlackCat", }, { "value": 15, "id": "777", "name": "WhiteCat", }]; const combinedItemsMap = (arr = []) => { const map = new Map(); arr.forEach(obj => { if (map.has(obj.id)) { map.get(obj.id).count++; } else { map.set(obj.id, {...obj, count: 1}); } }); return Array.from(map.values()); } console.log(combinedItemsMap(arr));
🌐
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
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"
  }
]
Find elsewhere
🌐
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.
🌐
Reddit
reddit.com › r/learnjavascript › merge array of objects that have the same properties
r/learnjavascript on Reddit: Merge Array of objects that have the same properties
January 22, 2022 -

I'm trying to merge multiple objects in an array into one object if they share the same ID. For instance...

var Students = [
    {
        ID : 1,
        Name : "John Doe",
        SponserID : 421,
        SponserName : "Mark"
    },
    {
        ID : 1,
        Name : "John Doe",
        SponserID : 341,
        SponserName : "James"
    },
    {
        ID : 2,
        Name : "James Law",
        SponserID : 421,
        SponserName : "Mark"
    }
]

I want to be able to combine the Obejcts with the same ID and make an object of the different properties in those objects so the result would look something like

var ModifiedStudents = [
    {
        ID : 1,
        Name : "John Doe",
        Sponsers : [
                    {
                    SponserID : 421,
                    SponserName : "Mark" 
                    },
                    {
                    SponserID : 341,
                    SponserName : "James" 
                    },
             ]
    },
    {
        ID : 2,
        Name : "James Law",
        SponserID : 421,
        SponserName : "Mark"
    }
]
Top answer
1 of 2
2

var arr = [
{
    "abc": [
        {
            "name": "test",
            "addr": "123",
       }
    ]
},
{
    "def": [
        {
            "first_name": "test",
            "last_name": "test"
        }
    ]
},
{
    "def": [
        {
            "first_name": "test1",
            "last_name": "test1"
        }
    ]
}]

const result = arr.reduce((acc, curr) => {        
    const key = Object.keys(curr)[0]
    const found = acc.find(i => i[key])
    if (!found) {
        acc.push(curr)
    } else {
        found[key] = [ ...found[key], ...curr[key] ]
    }
    return acc;
}, [])

console.log(result)

Code below should give the desired result.

ES6

arr.reduce((acc, curr) => {        
    const key = Object.keys(curr)[0]
    const found = acc.find(i => i[key])
    if (!found) {
        acc.push(curr)
    } else {
        found[key] = [ ...found[key], ...curr[key] ]
    }
    return acc;
}, [])

ES5

arr.reduce(function (acc, curr) {
  var key = Object.keys(curr)[0];
  var found = acc.find(function (i) {
    return i[key];
  });

  if (!found) {
    acc.push(curr);
  } else {
    found[key] = [].concat(found[key], curr[key]);
  }

  return acc;
}, []);

using filter instead of find

arr.reduce(function (acc, curr) {
  var key = Object.keys(curr)[0];
  var found = acc.filter(function (i) {
    return i[key];
  })[0];

  if (!found) {
    acc.push(curr);
  } else {
    found[key] = [].concat(found[key], curr[key]);
  }

  return acc;
}, []);
2 of 2
0

Using object and array

var arr = [{
    "abc": [{
      "name": "test",
      "addr": "123",
    }]
  },
  {
    "def": [{
      "first_name": "test",
      "last_name": "test"
    }]
  },
  {
    "def": [{
      "first_name": "test1",
      "last_name": "test1"
    }]
  }
]

var b = {}

arr.forEach(c => {
  var key = Object.keys(c)[0]
  var value = Object.values(c)[0]
  if (!b[key]) b[key] = []
  b[key].push(...value)
})

// b is resultant object

var c = []
Object.keys(b).forEach(v => {
  let a = {};
  a[v] = b[v];
  c.push(a)
})

// c is converting object to array

console.log(c)

Top answer
1 of 1
2

You can use reduce for that and iterate over the object keys of each object:

const res = array.reduce((a, b) => {
    Object.keys(b).forEach(k => {
        a[k] = (a[k] || 0) + b[k];
    });
    return a;
}, Object.create(null));

console.log(res);
<script>
const array = [
    {
        RT: 0.3396966806905289,
        Real: 0.03721461991442617,
        fired: 0.26138293747172237,
        'Real Madrid': 0.15767570563383954,
        Madrid: 0.2771992640023346,
        Zidane: 0.3218878635800967,
        'Florentino Perez': 0.31535141126767907,
        leave: 0.1632670522868711,
        manager: 0.12690962022792524,
        tancredipalmeri: 0.3218878635800967,
        Perez: 0.4543985280046692,
        Florentino: 0.44189852800466917
    },
    {
        Cannavaro: 0.2709492640023346,
        Ashley: 0.2771992640023346,
        'Ashley Cole': 0.15767570563383954,
        Casillas: 0.3896966806905289,
        Ronaldo: 0.22094926400233458,
        Zidane: 0.22094926400233458,
        Messi: 0.22094926400233458,
        Lampard: 0.22094926400233458,
        Iniesta: 0.22094926400233458,
        Terry: 0.2771992640023346,
        Henry: 0.19890866571173632,
        Cole: 0.22094926400233458,
        Ivanovic: 0.3218878635800967
    },
    {
        RT: 0.3396966806905289,
        effleurer: 0.22094926400233458,
        'n\'a': 0.2709492640023346,
        top: 0.13189246756926315,
        Zidane: 0.2709492640023346,
        entraineur: 0.22094926400233458,
        monde: 0.22094926400233458,
        au: 0.2271992640023346,
        'au monde': 0.20434237230050623,
        Mvssi10: 0.3218878635800967,
        JAMAIS: 0.2709492640023346
    },
    {
        RT: 0.3396966806905289,
        Real: 0.10790900513119943,
        FrenchRMCF: 0.3218878635800967,
        en: 0.2271992640023346,
        histoire: 0.2709492640023346,
        coach: 0.2271992640023346,
        au: 0.2271992640023346,
        Zidane: 0.22094926400233458,
        'en tant': 0.15767570563383954,
        tant: 0.22094926400233458
    }
]
</script>
Run code snippetEdit code snippet Hide Results Copy to answer Expand

🌐
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.