Use _.groupBy(), and then use _.mergeWith() to combine each group to a single object:

const data = [{"foo":"A","bar":[{"baz":"1","qux":"a"},{"baz":"2","qux":"b"}]},{"foo":"B","bar":[{"baz":"3","qux":"c"},{"baz":"4","qux":"d"}]},{"foo":"A","bar":[{"baz":"5","qux":"e"},{"baz":"6","qux":"f"}]},{"foo":"B","bar":[{"baz":"7","qux":"g"},{"baz":"8","qux":"h"}]}];

const result = _(data)
  .groupBy('foo')
  .map((g) => _.mergeWith({}, ...g, (obj, src) =>
      _.isArray(obj) ? obj.concat(src) : undefined))
  .value();
  
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Answer from Ori Drori on Stack Overflow
Top answer
1 of 6
65

Second highest voted answer doesn't do proper merge. If second array contains an unique property, it is not taken into account.

This approach does a proper merge.

Lodash

var a = [
  { userId:"p1", item:1},
  { userId:"p2", item:2},
  { userId:"p3", item:4}
];

var b = [
  { userId:"p1", profile:1},
  { userId:"p2", profile:2},
  { userId:"p4", profile:4}
];
var merged = _.merge(_.keyBy(a, 'userId'), _.keyBy(b, 'userId'));
var values = _.values(merged);
console.log(values);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
Run code snippetEdit code snippet Hide Results Copy to answer Expand

ES6+

// from https://stackoverflow.com/a/34749873/80766
const mergeDeep = (target, ...sources) => {
  if (!sources.length) return target;
  const source = sources.shift();

  if (target instanceof Object && source instanceof Object) {
    for (const key in source) {
      if (source[key] instanceof Object) {
        if (!target[key]) Object.assign(target, { [key]: {} });
        mergeDeep(target[key], source[key]);
      } else {
        Object.assign(target, { [key]: source[key] });
      }
    }
  }

  return mergeDeep(target, ...sources);
}

const a = [
  { userId:"p1", item:1},
  { userId:"p2", item:2},
  { userId:"p3", item:4}
];

const b = [
  { userId:"p1", profile:1},
  { userId:"p2", profile:2},
  { userId:"p4", profile:4}
];


const aKeyed = a.reduce((acc, cur) => ({ ...acc, [cur.userId]: cur }), {});
const bKeyed = b.reduce((acc, cur) => ({ ...acc, [cur.userId]: cur }), {});
const merged = mergeDeep(aKeyed, bKeyed);
const values = Object.values(merged);
console.log(values);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

2 of 6
44

You can use _.map(), _.assign() and _.find().

// Iterate over first array of objects
_.map(a, function(obj) {

    // add the properties from second array matching the userID
    // to the object from first array and return the updated object
    return _.assign(obj, _.find(b, {userId: obj.userId}));
});

Fiddle Demo

Show code snippet

var a = [{
    userId: "p1",
    item: 1
}, {
    userId: "p2",
    item: 2
}, {
    userId: "p3",
    item: 4
}];

var b = [{
    userId: "p1",
    profile: 1
}, {
    userId: "p2",
    profile: 2
}];

var arrResult = _.map(a, function(obj) {
    return _.assign(obj, _.find(b, {
        userId: obj.userId
    }));
});

console.log(arrResult);
document.getElementById('result').innerHTML = JSON.stringify(arrResult, 0, 4);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.1.0/lodash.min.js"></script>
<pre id="result"></pre>
Run code snippetEdit code snippet Hide Results Copy to answer Expand

🌐
StackBlitz
stackblitz.com › edit › lodash-merge-arrays-by-key
Lodash Merge Arrays By Key - StackBlitz
# lodash-merge-arrays-by-key · [Edit on StackBlitz ⚡️](https://stackblitz.com/edit/ lodash-merge-arrays-by-key) Enter to Rename, Shift+Enter to Preview · Compiling application & starting dev server… · Open Preview in new tab · Close Preview · Console · Clear on reload ·
🌐
IQCode
iqcode.com › code › javascript › how-to-merge-2-object-array-by-the-same-key-with-lodash
how to merge 2 object array by the same key with lodash Code Example
January 31, 2022 - Lodash var a = [ { userId:&quot;p1&quot;, item:1}, { userId:&quot;p2&quot;, item:2}, { userId:&quot;p3&quot;, item:4} ]; var b = [ ...
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › lodash-_-merge-method
Lodash _.merge() Method - GeeksforGeeks
Lodash _.merge() method is used to merge two or more objects, starting from the left-most to the right-most to create a parent mapping object. When two keys are the same, the generated object will have a value for the rightmost key.
Published: August 5, 2025
🌐
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)
🌐
Tim Mousk
timmousk.com › blog › lodash-merge
How Does The Lodash Merge Function Work? – Tim Mouskhelichvili
March 6, 2023 - The first argument (object) holds the destination object. The second and subsequent arguments hold the source objects. If two or more keys are the same, the generated object will take the value from the rightmost argument.
Find elsewhere
🌐
Blogger
khanh-ng.blogspot.com › 2015 › 02 › lodash-merge-without-overwriting.html
Khanh Nguyen's Blog: Lodash merge without overwriting
But what if you want to have your ... there is any conflict, i.e. there are 2 objects with the same key but different values. Lodash let you provide a customizer function to do just that....
Top answer
1 of 3
2
 const output = input.reduce((res, {dates}) => res.concat(dates), []);

You may use reduce to iterate over the objects and concat the results together. Theres no need to use loadash at all.

2 of 3
1

Using Lodash

You can use _.map() to get an array of the date objects. To merge the objects to a single one, will use _.merge(). We'll use _.partial() to add a target object, so we won't mutate the original data. In addition, We'll use the _.spread() method on the _.merge(), so it can handle an array of objects:

var data = [{"id":1,"oid":5,"dates":{"5":{"start_date":"12.30","end_date":"12.31"},"14":{"start_date":"01.01","end_date":"01.15"}}},{"id":2,"oid":5,"dates":{"17":{"start_date":"02.01","end_date":"02.20"},"19":{"start_date":"03.01","end_date":"03.10"}}}];


var result = _.spread(_.partial(_.merge, {}))(_.map(data, 'dates'));

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Using ES6

Pluck the dates by using Array#map on the Object#keys, and flatten by spreading into Object.assign:

var data = [{"id":1,"oid":5,"dates":{"5":{"start_date":"12.30","end_date":"12.31"},"14":{"start_date":"01.01","end_date":"01.15"}}},{"id":2,"oid":5,"dates":{"17":{"start_date":"02.01","end_date":"02.20"},"19":{"start_date":"03.01","end_date":"03.10"}}}];

var result = Object.assign({}, ...Object.keys(data).map((key) => data[key].dates));

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

🌐
MeasureThat
measurethat.net › Benchmarks › Show › 2522 › 0 › merge-object-by-key-from-array-with-lodash
Benchmark: merge object by key from array with lodash - MeasureThat.net
lodash merge vs object.assign vs spread with arrays · lodash merge vs object.assign vs spread vs manual forEach for array merging · lodash merge vs object.assign vs spread with deep values · lodash vs spread w/array · Merge objects with spread vs foreach & new ·
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

🌐
TutorialsPoint
tutorialspoint.com › lodash › lodash_merge.htm
Lodash - merge method
This method is like _.assign except that it recursively merges own and inherited enumerable string keyed properties of source objects into the destination object. Source properties that resolve to undefined are skipped if a destination value exists.
Top answer
1 of 5
3

This proposal does not alter the given data.

It creates new objects, first with just single data, later if more data should be grouped, it uses an array for batch and price.

var data = [{ product: 'ABC', productId: 'AB123', batch: 'BA1', price: '12' }, { product: 'ABC', productId: 'AB123', batch: 'BA2', price: '15' }, { product: 'XYZ', productId: 'AB124', batch: 'XY1', price: '124'}],
    merged = [];

data.forEach(function (a) {
    if (!this[a.productId]) {
        this[a.productId] =  { product: a.product, productId: a.productId, batch: a.batch, price: a.price };
        merged.push(this[a.productId]);
        return;
    }
    if (!Array.isArray(this[a.productId].batch)) {
        this[a.productId].batch = [this[a.productId].batch];
    }
    if (!Array.isArray(this[a.productId].price)) {
        this[a.productId].price = [this[a.productId].price];
    }
    this[a.productId].batch.push(a.batch);
    this[a.productId].price.push(a.price);
}, Object.create(null));

console.log(merged);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

2 of 5
1

You can make use of _.uniqWith to loop over the collection and get rid of duplicates. Apart from that, uniqWith grants you access to the objects themselves so you can tamper them as you like.

In this case, when a duplicate is found, I add its batch and price to the array of the original object, getting the desired result.

var arr = [{
  product: 'ABC',
  productId: 'AB123',
  batch: 'BA1',
  price: '12'
}, {
  product: 'ABC',
  productId: 'AB123',
  batch: 'BA2',
  price: '15'
}, {
  product: 'XYZ',
  productId: 'AB124',
  batch: 'XY1',
  price: '124'
}];

function addToArray(val1, val2) {
  return _.isArray(val1) ? val1.concat(val2) : [val1].concat(val2);
}

function modifyObjs(a, b) {
  b.batch = addToArray(b.batch, a.batch);
  b.price = addToArray(b.price, a.price);
  return true;
}

function predicateAndModifier(a, b) {
  return a.product === b.product && a.productId === b.productId && modifyObjs(a, b);
}

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

🌐
Cloudhadoop
cloudhadoop.com › home
Learn How to combine objects in javascripts/lodash
December 31, 2023 - extend method also do the same thing by copying object .properties. Extend method works like the same assignIn method in lodash · console.log(_.extend({ id: 3 }, { id: 5, name: "kiran" })); // returns {id: 5, name: "kiran"} Merge also merge the object properties into source and destination.