Ad

API Key With Colon, Parsing It Gives TypeError: ForEach Isn't A Function

- 1 answer

I'm trying to use New York Times API in order to get the Top Stories in JSON but I keep on getting a:

Uncaught TypeError: top.forEach is not a function

I feel like there's something wrong with the API key since it has : colons in the url. I even tried to encode it with %3A but it still doesn't work.

This is the basic url:

http://api.nytimes.com/svc/topstories/v2/home.json?api-key={API-KEY}

My function that grabs the data from the url: ```

function topStories(topStoriesURL) {
    $.getJSON(topStoriesURL, function(top) {
        top.forEach(function(data) {
            link = data.results.url;
                cardTitle = data.results.title;
                if(data.results.byline == "") { postedBy = data.results.source; }
                else { postedBy = data.results.byline; }
                imgSource = data.results.media[0].media-metadata[10].url;
                createCardElements();
        });
    });
}

I console.log(url) and when I click it inside Chrome console, it ignored the part of the key that comes after the colon. I've been debugging, but I can't seem to figure out the error.

Ad

Answer

Here is a version of the code that works.

function topStories(topStoriesURL) {
  $.getJSON(topStoriesURL, function(data) {
    if (data.error) {
      alert('error!'); // TODO: Add better error handling here
    } else {
      data.results.forEach(function(result) {
        var link = result.url,
          cardTitle = result.title,
          postedBy = result.byline == "" ? result.source : result.byline,
          hasMultimedia = (result.multimedia || []).length > 0,
          imgSource = hasMultimedia ? result.multimedia[result.multimedia.length - 1].url : null;
        createCardElement(link, cardTitle, postedBy, imgSource);
      });
    }
  });
}

function createCardElement(link, title, postedBy, imgSource) {
  // create a single card element here
  console.log('Creating a card with arguments of ', arguments);
}

topStories('http://api.nytimes.com/svc/topstories/v2/home.json?api-key=sample-key');
Ad
source: stackoverflow.com
Ad