Merge Array of Objects by Property using Lodash

benjiman picture benjiman · Aug 24, 2016 · Viewed 73.2k times · Source

I have two arrays of objects that represent email addresses that have a label and a value:

var original = [
  {
    label: 'private',
    value: '[email protected]'
  },
  {
    label: 'work',
    value: '[email protected]'
  }
];

var update = [
  {
    label: 'private',
    value: '[email protected]'
  },
  {
    label: 'school',
    value: '[email protected]'
  }
];

Now I want to compare and merge the two arrays by the label field, so that the result would look like this:

var result = [
  {
    label: 'private',
    value: '[email protected]'
  },
  {
    label: 'work',
    value: '[email protected]'
  },
  {
    label: 'school',
    value: '[email protected]'
  }
]

How can I do this e.g. using lodash?

Answer

Andreas picture Andreas · Aug 24, 2016

_.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: '[email protected]' },
  { label: 'work', value: '[email protected]' }
];

var update = [
  { label: 'private', value: '[email protected]' },
  { label: 'school', value: '[email protected]' }
];

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>