我正在使用 React 开发一些显示温度和降雨预报的天气小部件。我从 OpenWeather 获取数据,我的 json 响应如下所示:
//rainy day
0:{
main: {
temp:10}
rain: {
3h: 1000}
}
//sunny day
1:{
main: {
temp:10}
}
问题是 rain.3h 属性只有在它有一些数据时才会出现在返回的响应中,否则它会丢失。我的请求看起来像:
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);
}
}
我收到错误 类型错误:无法读取未定义的属性“3h”。 当响应中缺少该属性时,如何添加默认 rain:0
最佳答案
您可以使用三元运算符进行检查
let forecast = jsonResponse.list.map(
day => {
return {
temp: day.main.temp,
rain: day.rain?day.rain["3h"] : ''
}
}
)
关于javascript - 返回的 json 响应/javascript 中缺少属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46939262/