【发布时间】:2018-08-16 05:14:58
【问题描述】:
我正在处理一个 React 项目并尝试从 API 中提取 JSON 数据。我有一个搜索栏,我想制作它,以便用户可以在搜索栏中键入一个术语,然后将该术语发送到 NASA API 并返回适当的结果。
NASA API 看起来像 this。它有一系列对象,这就是我遇到问题的地方。我在通过对象映射时遇到问题(我知道 .map 仅适用于数组,我很可能需要使用 Object.keys 来遍历对象)。我无法完成此操作。
我的代码如下所示:
loadSearchResults = (event) => {
event.preventDefault();
var search = this.state.value;
axios.get(`https://images-api.nasa.gov/search?q=` + `search`)
.then(res => {
//const results = res.data.collection.items;
const results = res.data.collection.items;
this.setState = ({
results,
header: "Search Results"
});
console.log(results);
});
}
我能够控制台记录数据,但我不确定如何遍历对象并获取我想要的数据。我尝试过将 const 结果设置为 const results = res.data.collection.items.map() 或 res.data.collection.Object.keys() 等变体……但我无法弄清楚.
如何从数据数组对象中提取数据? IE。标题。描述等...
"items": [
{
"links": [
{
"href": "https://images-assets.nasa.gov/video/50 Years of Mars Exploration /50 Years of Mars Exploration .srt",
"rel": "captions"
}
],
"href": "https://images-assets.nasa.gov/video/50 Years of Mars Exploration /collection.json",
"data": [
{
"center": "HQ",
"description": "2015 marks 50 years of successful NASA missions to Mars starting with Mariner 4 in 1965. Since then, a total of 15 robotic missions led by various NASA centers have laid the groundwork for future human missions to the Red Planet. The journey to Mars continues with additional robotic missions planned for 2016 and 2020, and human missions in the 2030s.",
"nasa_id": "50 Years of Mars Exploration ",
"keywords": [
"Mars"
],
"date_created": "2015-08-20T00:00:00Z",
"title": "50 Years of Mars Exploration ",
"media_type": "video"
}
]
},
【问题讨论】:
-
需要提取哪些信息?由于
axios已经将 JSON 响应传递给对象,您可以简单地做this.setState({result:res.data}) -
Object.values()将为您提供没有密钥的内容数组。这有帮助吗? -
修复这个:
this.setState = ({ -
我正在尝试访问对象内的内容,即中心、描述等。
-
我需要使用 Object.keys 来访问它吗?
标签: json reactjs object iteration