API返回JSON对象,结果为数组,如何迭代它们?

时间:2018-03-11 14:11:59

标签: javascript arrays json loops

我试图创建一个简单的新闻Feed应用程序来练习使用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"
}

1 个答案:

答案 0 :(得分:0)

由于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`
    }
});