【问题标题】:API returns JSON object with results in an array, How to iterate through them?API 以数组形式返回 JSON 对象,如何遍历它们?
【发布时间】:2018-03-11 14:11:59
【问题描述】:

我正在尝试制作一个简单的新闻提要应用来练习使用 API。我已经提出了一个获取请求,但我无法弄清楚如何正确地遍历数组。我的目标只是能够获取作者和标题并将它们输出到 html 中的页面

Javascript

var url = 'https://newsapi.org/v2/top-headlines?' +
      'country=us&' +
      'apiKey=123DemoKey';
var req = new Request(url);
fetch(req)
    .then(function(response) {
        console.log(response.json());
    })

从 API 返回的数据片段

{
"status": "ok",
"totalResults": 20,
-"articles": [
-{
-"source": {
"id": "cnn",
"name": "CNN"
},
"author": "Sheena McKenzie, CNN",
"title": "Russian spy attack: Customers urged to wash clothes as traces of nerve agent found",
"description": "Customers at a restaurant and pub in Salisbury were urged to wash their clothes Sunday, after traces of the nerve agent used on Russian spy Sergei Skripal and his daughter were detected.",
"url": "https://www.cnn.com/2018/03/11/europe/russian-spy-attack-customers-told-to-wash-clothes-intl/index.html",
"urlToImage": "https://cdn.cnn.com/cnnnext/dam/assets/180306183502-russian-spy-critically-ill-salisbury-uk-investigation-black-pkg-00005819-super-tease.jpg",
"publishedAt": "2018-03-11T13:07:01Z"
}

【问题讨论】:

  • 嗯,JSON 让我有点困惑。 "articles" 数组在哪里终止?如果您只想遍历数组,Sean Denny 的答案是使用art.author、art.title 等来访问数据。或者,如果您想遍历这一切,您可以使用Object.keys() .您可以通过在 fetch() 中以编程方式设置元素来将数据显示到 HTML 中

标签: javascript arrays json loops


【解决方案1】:

由于 News API 返回 JSON,您可以照常解析它,然后使用 .forEach 或 for...of 循环遍历结果。

fetch('https://newsapi.org/v2/top-headlines')
.then(r => r.json())
.then(r => {
    r.articles.forEach(art => {
        // ... do something with `art`
    });

    for (const art of r.articles) {
        // ... do something with `art`
    }
});

【讨论】:

猜你喜欢
  • 2023-03-17
  • 1970-01-01
  • 2021-08-15
  • 2021-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-13
  • 2016-02-03
相关资源
最近更新 更多