Просто unionBy
вам не поможет, но groupBy
и merge
помогут.
(Я добавил несколько данных в пример ввода, чтобы доказать, что он работает как задумано.)
_ = require("lodash");
var original = [
{
label: "private",
value: "private@johndoe.com",
id: 21,
},
{ label: "public" },
{ label: "test3" },
];
var update = [
{
label: "private",
value: "me@johndoe.com",
uploadId: "jdsnl",
},
{ label: "test3", value: "update3" },
];
// Use groupBy over the merged originals and updates
// (in this order, so the groups in the output have
// the correct application order)
// to get an object mapping `label` to each group,
// then unwrap the object to just get a list of groups
// using values.
var groups = _.values(
_.groupBy(_.concat(original, update), "label"),
);
// map over the groups (lists), applying merge so that
// it is called e.g. for a group [a, b, c] with the
// arguments [{}, a, b, c], so that properties are merged
// into a new object from the original, then the update
// objects.
var merged = _.map(groups, group =>
_.merge.apply(null, _.concat([{}], group)),
);
console.log(merged);
Выход
[ { label: 'private',
value: 'me@johndoe.com',
id: 21,
uploadId: 'jdsnl' },
{ label: 'public' },
{ label: 'test3', value: 'update3' } ]
как и ожидалось.