Categories
JavaScript Answers

How to merge array of objects by property using JavaScript Lodash?

Spread the love

To merge array of objects by property using JavaScript Lodash, we use the unionBy function.

For instance, we write

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

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

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

to call unionBy with the update and original arrays and merge the objects into one by matching the label property.

A new array with the merged objects is returned.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *