I have a data set like so where there can be many objects in the array:
tableCols = [
{
"id": 50883,
"header": "ABC",
"operator": "Sum",
"order": 2
},
{
"id": 50884,
"header": "Leakage",
"operator": "Sum",
"order": 3
},
.....
]
And I have another data set like so where there can be many objects in the array:
dataArr = [
{
"id": 925095,
"grid_row_id": 170712,
"grid_col_id": 50883,
"data": "10",
"error_msg": null,
"locked": 1
},
{
"id": 926137,
"grid_row_id": 170712,
"grid_col_id": 50884,
"data": "34",
"error_msg": null,
"locked": 1
},
{
"id": 926137,
"grid_row_id": 170713,
"grid_col_id": 50883,
"data": "22",
"error_msg": null,
"locked": 1
},
{
"id": 926137,
"grid_row_id": 170713,
"grid_col_id": 50884,
"data": "100",
"error_msg": null,
"locked": 1
},
.....
]
Note that every single grid_col_id in the second array exists as an id in the first array.
I want to create another array like so:
formattedData = [
{
"ABC": 10,
"Leakage": 34,
....
},
{
"ABC": 22,
"Leakage": 100,
....
},
....
]
Essentially, for every item in dataArr, for all objects with the same grid_row_id, create an object in a new array where we have new key-value pairs where the key is equal to the header in tableCols where grid_col_id = id.
For example, in the dataArr above, we have 4 known objects, with grid_row_ids 170712 and 170713 (note that there could be more). The first object has grid_row_id 50883, which in tableCols with the id 50883 has headed ABC, so a new key is created the key as ABC and the value as 10 (because data = 10 in the dataArr object).
Hence why we have the following in formattedData:
"ABC": 10,
I have something which kind of works but it creates a new object for each item in dataArray instead of filtering through the array and creating a new object for every row:
let ogGrid = [];
let formattedData = [];
let newObj = {};
dataArr.forEach(row => {
tableCols.forEach(element => {
if(row.grid_col_id === element.id)
newObj[element.header] = Number(row.data);
});
})
ogGrid = {...newObj};
formattedData.push(ogGrid);
});
How would I be able to achieve the new structure?
formattedData = [{ "ABC": 10, "ABC": 22 }, { "Leakage": 34, "Leakage": 100,}]