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.