简体   繁体   English

API返回带有数组结果的JSON对象,如何遍历它们?

[英]API returns JSON object with results in an array, How to iterate through them?

I'm trying to make a simple news feed app to practise working with API's. 我正在尝试制作一个简单的新闻提要应用程序来练习使用API​​。 I've made a fetch request but I cant work out how to correctly iterate over the array. 我已经提出了获取请求,但是我无法弄清楚如何正确地遍历数组。 My objective is simply to be able to get the Author and title and output them to the page in html 我的目标仅仅是能够获得作者和标题并将其输出到html页面中

Javascript Java脚本

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());
    })

Snippet of Returned Data from API 从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"
}

Since News API returns JSON you can parse it as you did and then use .forEach or a for...of loop to iterate through the result. 由于News API返回JSON,因此您可以像以前一样解析它,然后使用.forEachfor...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`
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM