我正在使用React Native和Open Weather Map API构建一个小型天气应用程序。我从API调用中检索到的数据超出了我想要使用的范围,因此我仅解析出所需的部分并将它们存储在数组中。然后,我将数组设置为状态对象。我可以引用该对象,但是与其说我的数组是一个数组,不如说它是一个对象,因此不允许我在其上使用任何数组方法。我该如何解决?
//reponseData is the data retrieved from the API call; the data retrieved is an object with arrays and objects
within. The forecast data for the next five days is given in 3 hour increments,so you have a 40 item array of
data pieces. I loop through this list of 40 items,pull out just what I need...
let forecastArray = [];
for (let i=0; i<responseData.list.length; i++) {
let day = responseData.list[i].date
let high = responseData.list[i].weather[0].hiTemp
let low = responseData.list[i].weather[0].loTemp
let condition = responseData.list[i].sys.condition
forecastArray.push(day)
forecastArray.push(high)
forecastArray.push(low)
forecastArray.push(condition)
this.setState({
forecastData: forecastArray
})
当我登录时,我得到一个数组。...
console.warn("forecast is: ",this.state.forecastData)
OUTPUTS: forecast is: ["11-06-2019",52.5,47.3,"sunny","11-06-2019",63.9,39.7,...]
例如,引用this.state.forecastData [2]给我错误。所以我检查了this.state.forecast的类型以查看原因,并说该数组是一个Object?我需要进一步划分数组数据并对其进行操作。前几个项目(从ForecastData [0]到ForecastData [9]分别是针对11-06-2019下午3点,6pm,9pm的天气预报,因此我需要提取这些项目,获得最高和最低,等等。因为我什至无法引用数组中的项目,所以我不能这样做。
我尝试过的事情: 使用Object.entries和Object.assign方法,但这只是将项目拆分为几个数组,第一个项目是位置编号,第二个项目是数组项目内容。我试图在使用它的组件中操纵数组,但是它仍然是一个对象而不是数组,因此我无法引用各个项目。数据集足够大,我认为将40多个项目中的每个项目推入其自己的状态对象键中并不是最佳实践。