· 1 min read
Merge two arrays of objects by key
Index one side into a Map, then merge by id. The version that matches on array position only works by luck.
Two API calls return the same entities with different fields. Merging them by id is the usual need, and the usual snippet matches on index:
function mergeArrayObjects(left, right) {
return left.map((item, i) => {
if (item.id === right[i].id) {
return Object.assign({}, item, right[i]);
}
});
}
That works only while both arrays are sorted the same way and have the same length. One missing row on either side and every following pair is compared against the wrong object — and the undefined it returns gets silently filtered out by JSON.stringify.
The version that does not care about order
function mergeById(left, right) {
const byId = new Map(right.map((item) => [item.id, item]));
return left.map((item) => ({ ...item, ...byId.get(item.id) }));
}
The right side is indexed once, so the merge is linear instead of O(n²) for free. Objects on the left that have no match keep their original fields, because spreading undefined is a no-op.
Choosing the winner
{ ...item, ...match } lets the right side win on conflicting fields. Swap the order if the left side is authoritative, or pick fields explicitly:
return left.map((item) => {
const match = byId.get(item.id);
return match ? { ...item, views: match.views } : item;
});
That third form is the one to reach for in review: it says which fields the merge is allowed to change.
Building the key from several columns
Map needs one value, so compose it:
const key = (row) => `${row.tenantId}:${row.id}`;
Concatenating with : is fine as long as the parts cannot contain the separator.