000
000

Reputation: 99

jQuery $.ajax and $.each looping through array

I'm making a call to the NY Times article search API and would like to append it to an HTML element as a new list element. However I'm having trouble using the $.each() function and iterating through the JSON data. I'm trying to post a hyperlink and article snippet.

The error I'm getting is "Uncaught SyntaxError: Unexpected token" at data.response in "$.each(data, function(i, data.response)"

$.ajax({
  url: url,
  method: 'GET',
}).done(function(data) {
  $.each(data, function(i, data.response){
    $.each(data.response.docs, function(index, object){
      $nytElem.append('<li class ="article">'+
      '<a href='+ data.response.docs[index].web_url +'>' + data.response.docs[index].headline.main +
      '</a><p>' + data.response.docs[index].snippet + '</p></li>')
    });
  });
  console.log(data);
}).fail(function(err) {
  throw err;
});

The API returns an object with an array containing information for 10 articles. I've only posted 2 here for brevity. Any help would be appreciated!

    {
      "status": "OK",
      "copyright": "Copyright (c) 2017 The New York Times Company. All Rights Reserved.",
      "response": {
        "docs": [
          {
            "web_url": "https://www.nytimes.com/aponline/2017/09/05/world/asia/ap-as-taiwan-politics.html",
            "snippet": "Taiwan's president has appointed a new premier seen as willing to reach out to rival China amid ongoing tense relations.",
            "blog": {},
            "source": "AP",
            "multimedia": [],
            "headline": {
              "main": "Taiwan Appoints New Premier Amid Tense China Relations",
              "print_headline": "Taiwan Appoints New Premier Amid Tense China Relations"
            },
            "keywords": [],
            "pub_date": "2017-09-05T06:06:43+0000",
            "document_type": "article",
            "new_desk": "None",
            "section_name": "Asia Pacific",
            "byline": {
              "original": "By THE ASSOCIATED PRESS"
            },
            "type_of_material": "News",
            "_id": "59ae3f007c459f246b621bb9",
            "word_count": 131,
            "score": 1,
            "uri": "nyt://article/ae5b0e41-75b2-5a7e-972d-8a76bcd5c11a"
          },
          {
            "web_url": "https://www.nytimes.com/reuters/2017/09/05/business/05reuters-hyundai-motor-china.html",
            "snippet": "South Korea's Hyundai Motor said it had suspended production at one of its China factories on Tuesday after a supplier refused to provide parts due to delays in payment - its second such incident in as many weeks.",
            "blog": {},
            "source": "Reuters",
            "multimedia": [],
            "headline": {
              "main": "Hyundai Hit Again by Supply Disruption in China, One Plant Halted",
              "print_headline": "Hyundai Hit Again by Supply Disruption in China, One Plant Halted"
            },
            "keywords": [],
            "pub_date": "2017-09-05T06:03:30+0000",
            "document_type": "article",
            "new_desk": "None",
            "byline": {
              "original": "By REUTERS"
            },
            "type_of_material": "News",
            "_id": "59ae3e427c459f246b621bb8",
            "word_count": 516,
            "score": 1,
            "uri": "nyt://article/c519de15-1040-5fc7-b1ad-8e73aed33a47"
          }
       ],
       "meta": {
         "hits": 16210307,
         "offset": 0,
         "time": 1016
        }
     }
  }

Upvotes: 0

Views: 2289

Answers (1)

user5734311
user5734311

Reputation:

This is all you need:

.done(function(data) {
    $.each(data.response.docs, function(i, doc) {
        var $a = $('<a>').attr("href", doc.web_url).html(doc.headline.main);
        var $p = $('<p>').html(doc.snippet);
        var $li = $('<li>').addClass("article").append($a).append($p);
        $nytElem.append($li);
    });
});

The second parameter of the function you pass to $.each() is going to contain each element of the array you passed. So what you do is pass data.response.docs, which is the array of articles, then use doc (or similar) as param, and doc.[node] to access the object and its children inside the array.

Upvotes: 2

Related Questions