Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

property missing in returned json response / javascript

Im working in React on some weather widget which displays temp and rain forecast. Im fetching data from OpenWeather and my json response looks like:

//rainy day
0:{
  main: {
    temp:10}
  rain: {
    3h: 1000}
}
//sunny day
1:{
  main: {
    temp:10}
}

the problem is rain.3h property appears in returned response only when it has some data, otherwise its missing. My request looks like:

async getForecast(term) {
  const forecastUrl = "http://api.openweathermap.org/data/2.5/forecast?q=" + term + "&appid=" + apiKey + "&lang=us&units=metric&cnt=16";
  try {
    let response = await fetch(forecastUrl);
    if (response.ok) {
      let jsonResponse = await response.json();
      let forecast = jsonResponse.list.map(
        day => {
          return {
            temp: day.main.temp,
            rain: day.rain["3h"], // can't map missed property
          }
        }
      )
      return (forecast);
    }
  } catch (error) {
    console.log(error);
  }
}

And Im getting error TypeError: Cannot read property '3h' of undefined. How may I add default rain:0 when the property is missing from response

like image 737
JakubS Avatar asked Sep 14 '26 22:09

JakubS


1 Answers

You could do a check using ternary operator

 let forecast = jsonResponse.list.map(
        day => {
          return {
            temp: day.main.temp,
            rain: day.rain?day.rain["3h"] : ''
          }
        }
      )
like image 162
Sajeetharan Avatar answered Sep 17 '26 13:09

Sajeetharan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!