Check out this method for achieving the desired outcome. (A detailed explanation follows.)
const array1 = [
{
"document_id":"ABC123",
"document_title":"How to handle a Situation",
},
{
"document_id":"ABC678",
"document_title":"Changing to Status two",
},
{
"document_id":"ABC678",
"document_title":"Changing to Status two",
}
];
const array2 = [
{
"article_id":"ABC123",
"rank":0
},
{
"article_id":"ABC678",
"rank":1
}
];
const mergedMap = ([...array1, ...array2])
.reduce(
(acc, {document_id, article_id = document_id, ...others}) => {
acc[article_id] = {...(acc[article_id] || {article_id}), ...others};
return acc;
},
{}
);
console.log(Object.values(mergedMap));
Generate a new array containing all elements from both array1 and array2.
[...array1, ...array2]
Utilize Array.reduce
on the combined array.
[...array1, ...array2].reduce(
// function,
// initial value
)
The first parameter for Array.reduce
is a function that operates on each item in the array. It has four arguments, but we are focused on the first two:
- The value returned by the previous iteration (the accumulator)
- The current array entry.
We're utilizing object destructuring syntax on the second argument (the current array entry) to extract the article_id
with a default of document_id
, and capturing the remaining properties as others
.
(acc, {document_id, article_id = document_id, ...others}) => {
Merge the current item's properties into the accumulator's entry for its article_id
, creating the entry if needed using {article_id}
:
acc[article_id] = {...(acc[article_id] || {article_id}), ...others};
Return the updated accumulator for the subsequent iteration:
return acc;
The end result after running this reduce operation will be a map of article_id
to merged objects:
{
ABC123: {
article_id: 'ABC123',
rank: 0,
title: 'How to handle a Status',
},
ABC678: {
article_id: 'ABC678',
document_title: 'Changing to Status two',
rank: 1
}
}
We no longer need the keys in this object, so we extract the values as an array:
Object.values(mergedMap);
This will give us an array of objects:
[
{
"article_id": "ABC123",
"document_title": "How to handle a Status",
"rank": 0
},
{
"article_id": "ABC678",
"document_title": "Changing to Status two",
"rank": 1
}
]