I have two chat message arrays, each representing messages for a given date. I must merge these two arrays into a single object with the same date format. The object should contain all messages from both arrays, with the messages for each date merged.
Here is the data:
const data1 = {
messages: {
"27-04-2023": [
{
id: "SOkXFGtTwh",
},
{
id: "i3NrqNyG9P",
},
{
id: "lCmxr4rc5T",
},
]
}
};
const data2 = {
messages: {
"27-04-2023": [
{
id: "V9QzRgl6ji",
},
{
id: "K5wfD-kX8W",
}
],
"24-04-2023": [
{
id: "tuarzhHPwH",
},
{
id: "cbxu_dAeAj",
},
{
id: "9xJpEJGUnm",
}
]
},
};
How to merge them to get the following output?
const data1 = {
messages: {
"27-04-2023": [
{
id: "SOkXFGtTwh"
},
{
id: "i3NrqNyG9P"
},
{
id: "lCmxr4rc5T"
},
{
id: "V9QzRgl6ji"
},
{
id: "K5wfD-kX8W"
}
],
"24-04-2023": [
{
id: "tuarzhHPwH"
},
{
id: "cbxu_dAeAj"
},
{
id: "9xJpEJGUnm"
}
]
}
};
What would be the best way to perform such task?
2
Answers
You can consider using
for-in
and spread operator to merge 2 objects of arrays:This version merges any number of such objects into one, just allowing the property value from a later object override the same-named one from an earlier one, except for
messages
, which gets special handling: grabbing all themessages
properties, converting them into a flat list ofentries
, and folding the results back into a single object:If
messages
is your only property, you can remove theObject .assign
line. Conversely, if you also need special handling for other properties besidesmessages
, it’s easy to add additional ones parallel tomessages
.