mandiatutti
mandiatutti

Reputation: 57

Iterate through API response and display

I have this API: https://newsapi.org/v2/everything?q=supercars&apiKey=[MyApiKey]

I'd like to create a view that displays them with some information. I have to iterate on the articles array.

I'd like to replicate the api's info in my views tag. How can I do that? I can access the single info, but can't replicate all the news. With this syntax only the "Lamborgini Sian" news gets shown.

var result;
$(document).ready(function() {
  $.getJSON("https://newsapi.org/v2/everything?q=supercars&apiKey=[MyApiKey]", function(result) {
    console.log(result.totalResults);
    $(".title").text(result.articles[1].title);
    if (result.status == 'ok') {
      for (var i in result.totalResult) {
        $(".title").text(result.articles[i].title);
      }
    } else {
      window.alert("An error has occured");
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="articlesnum"></div>
  <br>
  <div class="title"></div>
  <!--
  <p class="p1">
    <div class="author1"></div> 
  </p>
  <p class="p2"></p>
  -->
</div>

Upvotes: 0

Views: 177

Answers (1)

mplungjan
mplungjan

Reputation: 178011

You need this

$(function() {
  $.getJSON("https://newsapi.org/v2/everything?q=supercars&apiKey=[MyApiKey]", show)
});

where show is something like shown below

NOTE: They return 20 results at a time so count page = i+20 (and test i*20 <= totalResults)

The trick is the use of backtics (`....`) to make a template literal

the ${varName} can then be dropped into the template

// remove THIS result when implementing
var result = {"status":"ok","totalResults":3,
"articles":[
{"source":{"id":"business-insider","name":"Business Insider"},"author":"Aj Caldwell and Matthew DeBord","title":"We spent a day driving the 2020 Nissan GT-R to see if it has the qualities of a good daily driver","description":"The GT-R is one of Nissan's most powerful and icon cars. Nissan advertises it as a supercar you can drive every day. While it may be limited in seating capacity and fuel economy, it has great storage and is comfortable enough to be a daily driver. Visit Busin…","url":"https://www.businessinsider.com/road-test-2020-nissan-gt-r-review-daily-driver-supercar-2019-8","urlToImage":"https://amp.businessinsider.com/images/5d5d6c2dcd97842a68678463-1920-960.jpg","publishedAt":"2019-08-29T13:00:00Z","content":"The following is a transcript of the video.\r\n Matt DeBord: And you'll see, when we floor it, you see it takes a little while to get up to speed there? You see that? \r\n Today, I'm testing out one of the world's most iconic supercars: the Nissan GT-R. I'm Matt … [+7968 chars]"},
{"source":{"id":null,"name":"Cnet.com"},"author":"Sean Szymkowski","title":"Lamborghini Sian is an electrified bull with 819 hp - Roadshow","description":"Lamborghini is using hybrid technology to create faster, more-powerful supercars.","url":"https://www.cnet.com/roadshow/pictures/lamborghini-sian-hybrid-supercar-reveal-frankfurt/","urlToImage":"https://cnet3.cbsistatic.com/img/ZkfyCWQq3850A9R57mZxYxLmAxo=/2019/09/03/88903d67-acfb-4ca9-a26e-27d096dd449e/lambo-ogi2.jpg","publishedAt":"2019-09-03T14:43:21Z","content":"Under the striking and jagged sheetmetal is a traditional V12 engine, but rather than a lithium-ion battery that is often the norm, Lamborghini said it's instead installed the first supercapacitor to operate in a hybrid powertrain."},
{"source":{"id":null,"name":"Cnet.com"},"author":"Roadshow staff","title":"2019 Frankfurt Motor Show: Roadshow's favorite debuts - Roadshow","description":"Wild concepts, frugal EVs and high-power supercars come together on our list of Frankfurt's best debuts.","url":"https://www.cnet.com/roadshow/news/best-of-2019-iaa-frankfurt-motor-show/","urlToImage":"https://cnet3.cbsistatic.com/img/eTEEZvgDnRRehWar9SuK9KeWQgA=/2019/09/03/166a6950-6f28-4992-b91f-a11463bbeeb6/ogi-mb.jpg","publishedAt":"2019-09-11T09:58:33Z","content":"Mercedes-Benz\r\nOnce every two years, the Frankfurt Motor Show earns its reputation as one of the biggest auto shows on the planet. Hundreds of manufacturers spread thousands of cars across the sprawling Messe Frankfurt am Main. While there's never a shortage … [+7139 chars]"}
]}


// you only need this function
function show(result) {
  if (result.status == 'ok') {
    let html = [];
    $.each(result.articles, function(_, article) {
      html.push(`<div>
                   <h3 class="title">${article.title}</h3>
                   <img src="${article.urlToImage}"/>
                   <p class="desc">${article.description}<br/>
                   <span class="author">${article.author}</span></p>
                 </div>`);
    });
    $("#articles").html(html)
  }
}


$(function() { 

// replace
show(result);
// with 
// $.getJSON("https://newsapi.org/v2/everything?q=supercars&apiKey=[MyApiKey]", show)});

});
.author {
  font-size: xx-small;
  color: green;
}

#articles img { height : 150px }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="articles"></div>

Upvotes: 2

Related Questions