I have a set of data which I'm trying to convert it into a different structure. I have almost reached the requirement but I'm stuck at the last part. Here's the code and what I have tried so far.
let array1 = [
{
aggr_type: "mean",
date: ['19 Apr', '20 Apr'],
mean: [13.87, 8.42],
name: "TEMPERATURE",
sum: [0.1, 0.2]
},
{
aggr_type: "sum",
date: ['19 Apr', '20 Apr'],
mean: [45.42, 55.22],
name: "HUMIDITY",
sum: [0.3, 0.5]
}
];
let names = [];
array1.forEach(el => {
names.push(el.name);
});
const myObj = names.reduce((a, key) => Object.assign(a, { [key]: null, date: null }), {});
// console.log(myObj);
// console.log(array1);
let arrays = []
for(i=0; i < array1[0].date.length; i++) {
array1.forEach(el => {
myObj.date = el.date[i];
myObj[el.name] = el.[el.aggr_type][i];
arrays.push(myObj);
});
}
console.log(arrays);
If this snippet isn't working use this codepen
I'm supposed to have the output like this.
[
{
'TEMPERATURE': '13.87',
'date': '19 Apr',
'HUMIDITY': '0.3'
},
{
'TEMPERATURE': '8.42',
'date': '20 Apr',
'HUMIDITY': '0.5'
}
];
But it only returns the last index. Is there any way to get the output like I've mentioned above.
NOTE: The values should be added the final output based on the aggr_type
aggr_type?