I have two sets of data that need to be combined and grouped a certain way.
First set of data:
let overallCert =
[
{
"id": "1",
"entity_id": "3",
"status": "Certified",
},
{
"id": "379",
"entity_id": "417",
"status": "Certified",
}
];
Second set of data:
let userCerts =
[
{
"id": "640",
"entity_id": "417",
"method": "Field Study",
"strand": "",
"date_completed": "2016-07-15T08:00:00.000Z"
},
{
"id": "814",
"entity_id": "417",
"method": "Field Study",
"date_completed": "2019-07-15T08:00:00.000Z"
},
{
"id": "844",
"entity_id": "3",
"method": "Online",
"date_completed": "2022-03-28T08:00:00.000Z"
},
{
"id": "845",
"entity_id": "3",
"method": "Field Study",
"date_completed": "2022-03-28T08:00:00.000Z"
}
];
I want to merge and group these arrays of objects by entity_id
to create this output below…
Desired output:
let desiredOutput =
[
[
[
{
"id": "640",
"entity_id": "417",
"method": "Field Study",
"date_completed": "2016-07-15T08:00:00.000Z"
},
{
"id": "814",
"entity_id": "417",
"method": "Field Study",
"date_completed": "2019-07-15T08:00:00.000Z"
},
],
[
{
"id": "379",
"entity_id": "417",
"status": "Certified",
}
]
],
[
[
{
"id": "844",
"entity_id": "3",
"method": "Online",
"date_completed": "2022-03-28T08:00:00.000Z"
},
{
"id": "845",
"entity_id": "3",
"method": "Field Study",
"date_completed": "2022-03-28T08:00:00.000Z"
}
],
[
{
"id": "379",
"entity_id": "417",
"status": "Certified",
}
]
]
];
So far, I have managed this:
let certsDataCombined = overallCert.map(item => ({ ...item,
0 : userCerts.filter(c => c.entity_id == item.entity_id)
}));
let userCertsGroupBy = groupBy(certsDataCombined, "entity_id");
function groupBy(arr, prop) {
const map = new Map(Array.from(arr, obj => [obj[prop], []]));
arr.forEach(obj => map.get(obj[prop]).push(obj));
return Array.from(map.values());
}
This code almost does the trick, but I need to encapsulate the overallCert
data in its own array, plus the nesting is a little off. Here is the current output: