Home > database >  Sum values of nested JSON objects in JavaScript filtered by dates
Sum values of nested JSON objects in JavaScript filtered by dates

Time:03-25

I have some JSON data in this structure:

"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"
                }
              }

Where I receive multiple readings in a day and for multiple days across the year.

I would like to be able to sum up all of the rainfall in the data and then also sum up all of the rainfall for a defined time period like yesterday, last month or between two dates.

I have tried to use map and reduce on the object, but I'm struggling to get it to work.

When I try and use a for loop, I can't seem to get passed the dates, for example:

for(data in weatherdata.DATA.Rainfall) {
       for(date in data) {
           console.log(data[date])
       }
    }

Any pointers would be much appreciated

CodePudding user response:

You don't need nested loops. Your first loop is iterating over the dates in the Rainfall object.

Then you need to use [date] as the key in that object

for (date in weatherdata.DATA.Rainfall) {
    console.log(weatherdata.DATA.Rainfall[date]);
}

To sum up all the rainfall amounts, you need a nested loop to process the times in each day.

const weatherdata = {
  "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"
        }
      }
    }
  }
};

let total_rainfall = 0;
let testdate = "2022-01-11";
Object.entries(weatherdata.DATA.Rainfall).forEach(([date, times]) => {
  if (date == testdate) {
    Object.values(times).forEach(data => total_rainfall  = parseFloat(data.MM));
  }
});

console.log(total_rainfall);

  • Related