【问题标题】:React iterate through an object inside of an array in JSONReact 遍历 JSON 中数组内的对象
【发布时间】: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


【解决方案1】:

你可以获取标题来搜索哪个.map

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

    }))

【讨论】:

    【解决方案2】:
    const results = [];
    
    res.items.forEach(item => {
        item.data.forEach(d => results.push(d));
    });
    

    【讨论】:

    • 我怎样才能访问对象中的那些属性呢?做 res.data.items.map(item => item.data.description);获取描述等..不起作用。我还需要在对象上使用 Object.keys 吗?
    • @NickKinlen 你真正想得到什么数据?
    • 我现在看到data也是一个数组
    • 编辑了我的答案
    • 我收到“扁平化不是函​​数”错误。我只是想访问对象内部的数据。
    猜你喜欢
    • 2020-12-15
    • 2018-10-31
    • 1970-01-01
    • 1970-01-01
    • 2015-03-13
    • 1970-01-01
    • 2018-08-26
    • 2017-12-23
    • 2021-01-30
    相关资源
    最近更新 更多