I have the following array of objects.
let arr = [
{
"alerts": {
"bp": {
"diaDiff": -20,
"Notes": null,
"resolveStatus": "0",
"sysDiff": 10
},
"threshold": {
"diaHigh": "110",
"diaLow": "60",
"sysHigh": "150",
"sysLow": "90"
},
"thresholdBpUnit": "mmHg"
},
"measurementDate": 1593934933000,
"actualUserID ": "11111"
},
{
"alerts": {
"bp": {
"diaDiff": -20,
"Notes": null,
"resolveStatus": "0",
"sysDiff": 10
},
"threshold": {
"diaHigh": "110",
"diaLow": "60",
"sysHigh": "150",
"sysLow": "90"
},
"thresholdBpUnit": "mmHg"
},
"measurementDate": 1593934933000,
"actualUserID ": "2222"
},
{
"alerts": {
"bp": {
"diaDiff": 80,
"Notes": null,
"resolveStatus": "0",
"sysDiff": 20
},
"threshold": {
"diaHigh": "120",
"diaLow": "60",
"sysHigh": "140",
"sysLow": "90"
},
"thresholdBpUnit": "mmHg"
},
"measurementDate": 6593934956000,
"actualUserID ": "11111"
},
{
"alerts": {
"bp": {
"diaDiff": 400,
"Notes": null,
"resolveStatus": "0",
"sysDiff": 10
},
"threshold": {
"diaHigh": "170",
"diaLow": "60",
"sysHigh": "190",
"sysLow": "90"
},
"thresholdBpUnit": "mmHg"
},
"measurementDate": 1593934944000,
"actualUserID ": "2222"
},
{
"alerts": {
"bp": {
"diaDiff": 300,
"Notes": null,
"resolveStatus": "0",
"sysDiff": 10
},
"threshold": {
"diaHigh": "570",
"diaLow": "60",
"sysHigh": "190",
"sysLow": "90"
},
"thresholdBpUnit": "mmHg"
},
"measurementDate": 8593934989000,
"actualUserID ": "6666"
}
];
I need to merge array object having same userID key and is expecting the following output.
let response = {
"success": true,
"data": {
"patient": [
{
"userID": "11111", // I need userID not actualUserID
"bpAlertData": [
{
alerts: { // object },
measurementDate: 1593934933000
},
{
alerts: { // object },
measurementDate: 6593934956000
}
]
},
{
"userID": "22222",
"bpAlertData": [
{
alerts: { // object },
measurementDate: 1593934944000
},
{
alerts: { // object },
measurementDate: 1593934933000
}
]
}
]
},
};
I tried the following but stuck with this.
arr.forEach((item) => {
let filteredData = response.data.patient.filter(patient => patient.userID === item.actualUserID);
if(filteredData.length) {
const existingIndex = response.data.patient.indexOf(filteredData[0]);
response.data.patient[existingIndex].bpAlertData = response.data.patient[existingIndex].bpAlertData.concat(item);
} else {
response.data.patient.push(item);
}
});
console.log(response.data.patient);
Instead of actualUserID, I am expecting userID in the response. Also how can we push these data into bpAlertData. So can somebody help me with this, as I am stuck with this for a long time. Any help would be really appreciated.