【发布时间】:2021-08-27 03:40:42
【问题描述】:
我正在尝试从 nasa 开放 api 之一中获取这些数组 -> https://api.nasa.gov/neo/rest/v1/feed?start_date=START_DATE&end_date=END_DATE&api_key=API_KEY
我在参数中有一个动态日期,因此返回的对象与日期匹配,有什么方法可以使用我的日期(即使它是一个字符串)并将其转换为“键”值,以便我可以动态获取我需要什么物品?
like => "2021-08-26" 将引用 { 2021-08-26: [{},{},{}...] }
到目前为止,我已将我的代码包含在我尝试过的内容中,目前我正在尝试使用 forEach 选择 {near_earth_objects} 内的所有键,但我仍然收到错误 data.near_earth_objects.forEach is not a function
constructor(){
super();
this.state={
asteroids:[],
time: []
}
}
//grab the current time (year-month-day) and store it in the state
componentWillMount(){
var today = new Date();
var start = today.getFullYear()+'-'+0+(today.getMonth()+1)+'-'+today.getDate();
var end = today.getFullYear()+'-'+0+(today.getMonth()+1)+'-'+(today.getDate()+1);
this.setState({time: [start,end]})
}
componentDidMount(){
fetch(`https://api.nasa.gov/neo/rest/v1/feed?start_date=${this.state.time[0]}&end_date=${this.state.time[1]}&api_key=ipAxYzaENbqRKb7GgzFPcH6QUBsHXY3QKB7uXOf5`
)
.then(response => response.json())
.then((data) => {
let asteroids = []
data.near_earth_objects.forEach((arr)=>{
asteroids.push(arr)
})
this.setState({asteroids:asteroids})
});
}
这是我尝试访问的记录数据的示例
【问题讨论】:
-
检查您的响应日志,
near_earth_objects不是数组,因此无法迭代。
标签: reactjs object react-hooks key