(This scenario is a bit more intricate compared to a previous query)
Here we have an array called originalArrayData:
originalArrayData = [{
"16": {
"id": 22,
"grid_row_id": 5,
"grid_col_id": 16,
"data": "10",
"created_at": "rertte",
"error_mgs": null
},
"header": "BUTTERFLY HEADER",
"id": 5
},
{
"17": {
"id": 31,
"grid_row_id": 9,
"grid_col_id": 16,
"data": "14",
"created_at": "rtyhtyjtdyj",
"error_mgs": null
},
"header": "BUTTERFLY HEADER",
"id": 6
},
{
"18": {
"id": 35,
"grid_row_id": 9,
"grid_col_id": 12,
"data": "55",
"created_at": "thrtuhrs",
"error_mgs": null
},
"header": "PARROT HEADER",
"id": 6
},
{
"19": {
"id": 36,
"grid_row_id": 9,
"grid_col_id": 12,
"data": "31",
"created_at": "rtyhtyjtdyj",
"error_mgs": null
},
"header": "PARROT HEADER",
"id": 7
},
{
"20": {
"id": 36,
"grid_row_id": 9,
"grid_col_id": 14,
"data": "31",
"created_at": "rtyhtyjtdyj",
"error_mgs": null
},
"header": "OTHER HEADER",
"id": 7
}...........
Let's assume we have an array of ids (these numbers could be random and there isn't always 2. There could be 1, 3, etc. array items)
arrayOfIds: [16 , 12]
If the value of grid_col_id exists in arrayOfIds, then for each object with the same grid_col_id, how can I generate a new array with new keys created using the "header" value, and the values of those keys being the sum of the "data" value from all items with the same grid_col_id.
TARGET / EXPECTED OUTPUT:
[{ "butterflyheader": 24, "parrotheader": 86, "category": "None"}]
EXPLANATION: If you examine each item in originalArrayData (for this example there are 4, but there can be many), the first 2 items share the same grid_col_id and header. For these two, the "data" equals to "10" and "14", which adds up to 24. Therefore, you obtain "butterflyheader": 24.
The same principle applies to parrotheader. All new keys are derived by converting the original "header" values into lowercase without spaces.
The element with the header "OTHER HEADER" is not included because its grid_col_id does not match any in arrayOfIds. "category": "None" remains constant and can be 'hard coded' into the new array.
To address this problem, I've formulated the following code:
// creates an array of all innermost objects in the original array
let tableDataFiltered = originalArrayData.map(item =>
Object.values(item).filter(item => typeof item === "object")
).flat()
// Retrieve all items with relevant grid_col_id
tableDataFiltered.filter(item => arrayOfIds.includes(item.grid_col_id))
// Headers to use as keys
let headersAsKeys = tableDataFiltered.forEach(item => {
item.header.toLowerCase().split(' ').join('')
})
Object.values(tableDataFiltered.reduce((acc, curr) => {
acc[curr.category] = 'None';
headersAsKeys.forEach(key => {
acc[curr.category][key] += curr[key];
})
return acc;
}, {}));
However, it returns an error stating that headersAsKeys.forEach is not a function.
How can I acquire the desired target array? =>
[{ "butterflyheader": 24, "parrotheader": 86, "category": "None"}]