Home > Blockchain >  Javascript function loops too many times and returns undefined
Javascript function loops too many times and returns undefined

Time:03-26

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.

CodePudding user response:

Just use the groupedDay after you are done witht he data, forEach does not have a return value, it will always be undefined

const data = {"Sensor": "14829304","DATA": {"Rainfall": {
"2022-01-11": {"T1": {"MM": "1","CONFIRMED": "T"},"T2": {"MM": "1","CONFIRMED": "T"}},
"2022-01-12": {"T1": {"MM": "2","CONFIRMED": "T"},"T2": {"MM": "2","CONFIRMED": "T"}},
"2022-01-13": {"T1": {"MM": "3","CONFIRMED": "T"},"T2": {"MM": "3","CONFIRMED": "T"}}},
"Temperature": {"2022-01-11": {"T1": {"MM": "9.32","CONFIRMED": "T"},"T2": {"MM": "9.44","CONFIRMED": "T"}}}}}

let groupedDay = {};

Object.entries(data.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)

CodePudding user response:

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).

  • Related