React在JSON中遍历数组内的对象

时间:2018-03-07 23:48:55

标签: json reactjs object iteration

我正在研究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);
  });

}

我能够console.log数据,但我不知道如何遍历对象并获取我想要的数据。我尝试过将const结果设置为const results = res.data.collection.items.map()或res.data.collection.Object.keys()等等的变体......但我无法弄明白

如何从数据数组对象中提取数据?即标题。 descriptiong等...

"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"
      }
    ]
  },

2 个答案:

答案 0 :(得分:0)

你可以获得搜索哪个.map

的标题
   results: results.map(results => ({
       title : results.data[0].title,
       description : results.data[0].description,

    }))

答案 1 :(得分:0)

const results = [];

res.items.forEach(item => {
    item.data.forEach(d => results.push(d));
});