I have some JSON data in this format
"Sensor": "14829304",
"DATA": {
"Rainfall": {
"2022-01-11": {
"T1": {
"MM": "3.94",
"CONFIRMED": "T"
},
"T2": {
"MM": "3.91",
"CONFIRMED": "T"
}
}
},
"Temperature": {
"2022-01-11": {
"T1": {
"MM": "9.32",
"CONFIRMED": "T"
},
"T2": {
"MM": "9.44",
"CONFIRMED": "T"
}
}
What I am trying to achieve is to sum up all of the MM for rainfall grouped by date. The problem is, my attempt isn't looping over all of the dates once, but loops over how many days there are.
My attempt is
let groupedDay = {};
const dailyRainfall = Object.entries(weatherdata.DATA.Rainfall).forEach(([day, times]) => {
if (groupedDay[day] == null) groupedDay[day] = 0
Object.values(times).forEach(data => {
if (data.MM != null) groupedDay[day] += parseFloat(data.MM)
})
//console.log(groupedDay)
return groupedDay
})
console.log(dailyRainfall)
The other problem I have is that the function returns undefined, but I can console log the groupedDay inside the function. I want it to return:
{ '2022-01-11': xxxx,
'2022-01-12': yyyy,
'2022-01-13': zzzz
}
Any pointers would be gratefully received.
The problem is that forEach
returns undefined, even if the callback function returns something. The correct way is not console.log(dailyRainfall)
but console.log(groupedDay)
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments