If you want to merge 2 arrays of objects in JavaScript. You can use this one line trick

Array.prototype.push.apply(arr1,arr2);

For Example

var arr1 = [{name: "lang", value: "English"},{name: "age", value: "18"}];
var arr2 = [{name : "childs", value: '5'}, {name: "lang", value: "German"}];

Array.prototype.push.apply(arr1,arr2); 

console.log(arr1);  // final merged result will be in arr1

Output:

[{"name":"lang","value":"English"},
{"name":"age","value":"18"},
{"name":"childs","value":"5"},
{"name":"lang","value":"German"}]
Answer from Jahanzaib Aslam on Stack Overflow
Top answer
1 of 2
3

A short review;

  • This code looks incredibly complicated for what you want to achieve, sometimes a few for loops beat the functional approach
  • array is a global variable (not var or set or const), that is a bad thing
  • If a function is not inline, I would encourage you to use the function keyword
  • I am not sure mergeLines is a great name, perhaps mergeIds ?

array = [{
    id: 1,
    items: [1, 2, 3]
  },
  {
    id: 2,
    items: [1, 2]
  },
  {
    id: 1,
    items: [4]
  },
  {
    id: 3,
    items: [1]
  },
];

function mergeIds(list){
  const out = [];
  for(entry of list){
    const existingEntry = out.find(o => o.id === entry.id);
    if(existingEntry){
      existingEntry.items = existingEntry.items.concat(entry.items);
    } else {
      out.push(entry);
    }
  }
  
  return out;
}

console.log(mergeIds(array));

2 of 2
6

You can reduce the computational complexity to O(n) by putting the intermediate arrays into an object indexed by id. This way, for every array item, you just need to look up the id property on the object, and don't need to search through every item in the array for a possible match:

array = [{
    id: 1,
    items: [1, 2, 3]
  },
  {
    id: 2,
    items: [1, 2]
  },
  {
    id: 1,
    items: [4]
  },
  {
    id: 3,
    items: [1]
  },
];

const mergeIds = (list) => {
  const subarrsById = {};
  for (const { id, items } of list) {
    if (!subarrsById[id]) {
      subarrsById[id] = { id, items: [...items] };
    } else {
      subarrsById[id].items.push(...items);
    }
  }
  return Object.values(subarrsById);
}

console.log(mergeIds(array));

One caveat - this will result in the output array being sorted by ascending array index, rather than by order of occurrence in the original array (because that's how object keys are arranged). If that's an issue, you can use a Map instead.

array = [{
    id: 1,
    items: [1, 2, 3]
  },
  {
    id: 2,
    items: [1, 2]
  },
  {
    id: 1,
    items: [4]
  },
  {
    id: 3,
    items: [1]
  },
];

const mergeIds = (list) => {
  const subarrsById = new Map();
  for (const { id, items } of list) {
    if (!subarrsById.has(id)) {
      subarrsById.set(id, { id, items: [...items] });
    } else {
      subarrsById.get(id).items.push(...items);
    }
  }
  return [...subarrsById.values()];
}

console.log(mergeIds(array));

A suggestion regarding your original code:

  processedIds.indexOf(elementId) === -1

When you want to check if an array contains an element, it's more natural to use .includes rather than an .indexOf check against -1.

Also, when creating a collection of processed primitives (like the IDs here), and you need to regularly check that collection to see if a particular primitive has been processed yet, consider using a Set and Set#has (O(1)) instead of an array and Array#includes (O(n)).

Discussions

javascript - Merge arrays from object property in an object array - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Ask questions, find answers and collaborate at work with Stack Overflow for Teams More on stackoverflow.com
🌐 stackoverflow.com
javascript - Merge Array of Objects by Property using Lodash - Stack Overflow
So for example: [ { label: 'private', ... get merged with the properties from the new value. 2016-08-31T02:41:59.29Z+00:00 ... what if I have 20 or more arrays? I can't find a way to dynamically pass the arrays as arguments in a loop. Any ideas? 2021-08-09T16:34:27.927Z+00:00 ... Save this answer. ... Show activity on this post. Convert the lists to objects keyed by label, merge ... More on stackoverflow.com
🌐 stackoverflow.com
javascript - Merge objects in array based on property - Stack Overflow
I have an array like so which i am trying to merge so any object that has the name property the same will after the merge contain a list of merged objects var array = [ {name: "One", myL... More on stackoverflow.com
🌐 stackoverflow.com
Merge Array of objects that have the same properties
I am retaining your spelling quirks here. First create an object whose keys are the student IDs: const studentsByID = Students.reduce( (obj, { ID, Name, SponserID, SponserName }) => { if (!obj.hasOwnProperty(ID)) { obj[ID] = { ID, Name, Sponsers: [] }; } obj[ID].Sponsers = [ ...obj[ID].Sponsers, { SponserID, SponserName } ]; return obj; }, {} ); Then your desired result is its values: const ModifiedStudents = Object.values(studentsByID); More on reddit.com
🌐 r/learnjavascript
3
2
January 22, 2022
🌐
SitePoint
sitepoint.com › blog › javascript › how to merge objects in javascript
How to Merge Objects in JavaScript — SitePoint
November 5, 2024 - This is because when an object ... target object, its value is replaced with the new value. Yes, arrays can be merged in JavaScript using similar methods to objects....
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-merge-array-of-objects-by-property-using-lodash
How to Merge Array of Objects by Property using Lodash? | GeeksforGeeks
August 22, 2024 - For example, if you have a list of user objects and you want to combine them into a single object based on a unique property, Lodash provides useful functions to simplify this process. Below are different approaches to merging objects in an array by a specific property using Lodash:
Top answer
1 of 7
122

_.unionBy():
This method is like _.union except that it accepts iteratee which is invoked for each element of each arrays to generate the criterion by which uniqueness is computed. Result values are chosen from the first array in which the value occurs.

var original = [
  { label: 'private', value: 'private@johndoe.com' },
  { label: 'work', value: 'work@johndoe.com' }
];

var update = [
  { label: 'private', value: 'me@johndoe.com' },
  { label: 'school', value: 'schol@johndoe.com' }
];

var result = _.unionBy(update, original, "label");

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
Run code snippetEdit code snippet Hide Results Copy to answer Expand

2 of 7
5

Convert the lists to objects keyed by label, merge them by _.assign, and convert it back to an array. It will even retain order of the items on most browsers.

var original = [
  {
    label: 'private',
    value: 'private@johndoe.com'
  },
  {
    label: 'work',
    value: 'work@johndoe.com'
  }
];

var update = [
  {
    label: 'private',
    value: 'me@johndoe.com'
  },
  {
    label: 'school',
    value: 'schol@johndoe.com'
  }
];

console.log(
  _.map(
    _.assign(
      _.mapKeys(original, v => v.label),
      _.mapKeys(update, v => v.label)
    )
  )
);


// or remove more duplicated code using spread

console.log(
  _.map(
    _.assign(
      ...[original, update].map(
        coll => _.mapKeys(coll, v => v.label)
      )
    )
  )
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.js"></script>
Run code snippetEdit code snippet Hide Results Copy to answer Expand

Find elsewhere
🌐
JavaScript Tutorial
javascripttutorial.net › home › javascript merge objects
How to Merge Objects in JavaScript
March 29, 2020 - If objects have a property with the same name, then the right-most object property overwrites the previous one. For example: let job = { jobTitle: 'JavaScript Developer', country: 'USA' }; let location = { city: 'London', country: 'England' ...
🌐
Go Make Things
gomakethings.com › merging-arrays-and-objects-with-vanilla-javascript
Merging arrays and objects with vanilla JavaScript | Go Make Things
January 4, 2023 - For example, here, both our objects contain an array of spells. let merlin = { job: 'Wizard', spells: ['Dancing teacups', 'Disappear'] }; let radagast = { job: 'Druid', spells: ['Talk to animals', 'Navigate'] }; let mergedWizards = Object.assign({}, merlin, radagast); When merging these together, the radagast.spells array completely overwrites the merlin.spells array. They’re not merged together. In a deep merge, the properties of the spells arrays would be merged together.
🌐
YouTube
youtube.com › watch
Merge Properties of Multiple JavaScript Objects | JavaScript Arrays & Objects for Beginners - YouTube
Can we have a new object that will have properties from multiple objects, in JavaScript? This is very important concept in ES6. You gonna see it and use it i...
Published: January 10, 2022
🌐
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"
    }
]
🌐
Flavio Copes
flaviocopes.com › home › javascript › how to merge two objects in javascript
How to merge two objects in JavaScript - Flavio Copes
September 18, 2026 - The best solution in this case is to use Lodash and its merge() method, which will perform a deeper merge, recursively merging object properties and arrays: import merge from 'lodash.merge' const merged = merge({}, person, update) // { name: ...
🌐
ITNEXT
itnext.io › merge-javascript-objects-in-an-array-with-different-defined-properties-5c1e2c3ca634
Merge JavaScript Objects in an Array with Different Defined Properties | by Paige Niedringhaus | ITNEXT
July 6, 2022 - Merge JavaScript Objects in an Array with Different Defined Properties Array.reduce() is the solution to combine objects that share a key, but not necessarily properties. Introduction At work …
🌐
Stack Overflow
stackoverflow.com › questions › 32481446 › merge-array-of-javascript-objects-by-property-key
jquery - Merge array of javascript objects by property key - Stack Overflow
What you'd want to do first is build a hash with Fieldname as key, and an array as value. Then you'd want to use reduce to add the values into the hash and array. Then you can transform it into an array using Object.keys and map.
🌐
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 - If it does, you can add it to the accumulator object, combining it with any existing object that has the same key. This will result in a single object for each unique value of the key property.
🌐
Medium
daviddalbusco.medium.com › merge-two-objects-and-array-to-object-in-javascript-79580583727a
Merge Two Objects And Array To Object In JavaScript | by David Dal Busco | Medium
April 3, 2020 - No more loops, comparison or rocket science, the merge operation can be written in a single line of code. It is also worth to notice that in case both objects would contain the same key, the value of the last object, “the one on the right in the line of code”, is the winning value.
Top answer
1 of 14
21

I came here looking for exactly this, saw @Gruff Bunny 's technique and wondered if 'lodash' wouldn't perhaps be a superior option even to 'underscore'?

Lo and behold :

let result = _.unionBy(updatingArr, origArr, 'name');
2 of 14
11

You could use Array#map in combination with Array#reduce

var origArr = [{ name: 'Trump', isRunning: true }, { name: 'Cruz', isRunning: true }, { name: 'Kasich', isRunning: true }],
    updatingArr = [{ name: 'Cruz', isRunning: false }, { name: 'Kasich', isRunning: false }],
    NEWArr = origArr.map(function (a) {
        return this[a.name] || a;
    }, updatingArr.reduce(function (r, a) {
        r[a.name] = a;
        return r;
    }, Object.create(null)));

document.write('<pre>' + JSON.stringify(NEWArr, 0, 4) + '</pre>');

UPDATE 2022

Using an object with name as hash and mapping the original array by taking the update from hash table or the original object.

const
    origArr = [{ name: 'Trump', isRunning: true }, { name: 'Cruz', isRunning: true }, { name: 'Kasich', isRunning: true }],
    updatingArr = [{ name: 'Cruz', isRunning: false }, { name: 'Kasich', isRunning: false }],
    updates = Object.fromEntries(updatingArr.map(o => [o.name, o])),
    result = origArr.map(o => updates[o.name] || o);

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

Another approach by using Map.

This approach works for objects who are only in the updating array as well.

const
    origArr = [{ name: 'Trump', isRunning: true }, { name: 'Cruz', isRunning: true }, { name: 'Kasich', isRunning: true }],
    updatingArr = [{ name: 'Cruz', isRunning: false }, { name: 'Kasich', isRunning: false }],
    result = Array.from([...origArr, ...updatingArr]
        .reduce((m, o) => m.set(o.name, o), new Map)
        .values()
    );

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

🌐
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 deepMerge = (a, b, fn) => [...new Set([...Object.keys(a), ...Object.keys(b)])].reduce( (acc, key) => ({ ...acc, [key]: fn(key, a[key], b[key]) }), {} ); const obj1 = { a: true, b: [1, 2, 3], c: { d: 4, e: 5 }, f: 'foo', }; const obj2 = { a: false, b: [4, 5, 6], c: { d: 6, g: 7 }, f: 'bar', }; const concatFn = (key, a, b) => { if (Array.isArray(a) && Array.isArray(b)) return a.concat(b); if (typeof a === 'object' && typeof b === 'object') return deepMerge(a, b, concatFn); if (typeof a === 'string' && typeof b === 'string') return [a, b].join(' '); return b ?? a; }; deepMerge(obj1, obj2, concatFn); // { // a: false, // b: [ 1, 2, 3, 4, 5, 6 ] // c: { d: 6, e: 5, g: 7 }, // f: 'foo bar' // } ... Master array manipulation in JavaScript with this ES6 article collection. ... Learn how to merge two arrays of objects, while combining objects based on a specified key.
🌐
Go Make Things
gomakethings.com › articles › how-to-deep-merge-arrays-and-objects-with-javascript
How to deep merge arrays and objects with JavaScript | Go Make Things
April 27, 2023 - If the key already exists in the ... them together. To do that, we’ll pass the clone[key] and the value back into the deepMerge() function, and assign the returned value to the clone[key] property....