Struggling to create an array of objects based on another array of objects. I attempted to use flatMap and then reduce, but encountered an issue when I tried to collect multiple statuses in one object. Below is what I have attempted and the desired result I aim to achieve:
My Initial Data:
const data = [
{
"timestamp": "2021-08-31T15:29:18Z",
"result": [
{
"label": "Not Covered",
"value": 132
}
]
},
{
"timestamp": "2021-09-30T15:29:18Z",
"result": [
{
"label": "Not Covered",
"value": 135
}
]
},
{
"timestamp": "2021-10-31T16:29:18Z",
"result": [
{
"label": "Not Covered",
"value": 135
}
]
}
]
Desired Output:
[
{
"Not Covered": 132,
"Active": 0,
"Expiring Soon": 0,
"timestamp": "2021-08-31T15:29:18Z"
},
{
"Not Covered": 135,
"Active": 0,
"Expiring Soon": 0,
"timestamp": "2021-09-30T15:29:18Z"
},
{
"Not Covered": 135,
"Active": 0,
"Expiring Soon": 0,
"timestamp": "2021-10-31T16:29:18Z"
}
]
Current Approach:
let flattenedResult = data.flatMap(({result, ...r}) => result.map(o => ({ ...o, ...r})));
const chartData = flattenedResult.reduce((acc, item) => {
const {timestamp, value, label} = item;
acc.push({timestamp, "Not Covered": "Not Covered" === label ? value : 0, "Active": "Active" === label ? value : 0, "Expiring Soon": "Expiring Soon" === label ? value : 0});
return acc;
}, []);
Current Output:
[
{
"timestamp": "2021-08-31T15:29:18Z",
"Not Covered": 132,
"Active": 0,
"Expiring Soon": 0
},
{
"timestamp": "2021-09-30T15:29:18Z",
"Not Covered": 135,
"Active": 0,
"Expiring Soon": 0
},
{
"timestamp": "2021-10-31T16:29:18Z",
"Not Covered": 135,
"Active": 0,
"Expiring Soon": 0
}
]