我正在使用 OpenWeather API 5 天 3 小时预报,我的响应 JSON 为我提供了数组中的 40 个项目,其中的日期格式为“dt_txt”:“2018-11-22 15:00:00”目的。 我的问题是我想每天(每天 15 点)渲染一个对象,而不是每 3 小时渲染一次。如何过滤数组以每天 15:00 返回 1 个对象?
我的代码如下所示;
handleFormSubmit = e => {
e.preventDefault();
fetch(
"https://api.openweathermap.org/data/2.5/forecast?q=" +
this.state.userInput +
"&units=metric&APPID="
)
.then(results => {
return results.json();
})
.then(data => {
let days = data.list
.filter(day => {
return day.dt_txt === **???????insert help here?????**;
})
.map((day, index) => {
return (
<div key={index}>
<div className="card WeatherDays" style={{ paddingTop: 20 }}>
<p>{day.dt_txt.slice(5, 16)}</p>
<p style={pStyle}>{day.main.temp}°</p>
{day.main.temp >= 15 ? (
<i className="fas fa-sun icons fa-5x" />
) : (
<i className="fas fa-cloud-sun-rain fa-5x" />
)}
</div>
</div>
);
});
this.setState(() => {
return {
days: days,
userInput: ""
};
});
})
.catch(error => {
let errors = error;
});
};
最佳答案
由于 dt_txt 是一个字符串,简单的 bool 检查就足够了。
.filter(day => {
return day.dt_txt.endsWith("15:00:00")
})
关于javascript - 过滤 API 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53431440/