Nathan
Nathan

Reputation: 87

How to exclude non existent JSON data with Javascript?

I'm using JavaScript Fetch to load some JSON data. I would like to display the data neatly in a HTML document.

I've had some troubles parsing some of the content. Most of the data objects I am trying to parse contain images, I need to load these. The problem arises when an object DOESN'T contain an image. What is happening at the moment is the first three images are loading (because they exist), then the fourth object doesn't have an image, and loop stops loading the rest (5th, 6th etc) of the images.

Can someone maybe take a look at this and give me nudge in the right direction?

fetch(url).then(function(response) {
    return response.json();
    JSON.stringify(data);
  })
  .then(function(data) {
    console.log(data);
    for (var i = 0; i < data.length; i++) {
      var listItem = document.createElement("li");
      var imgGrabber = document.createElement("img");

      listItem.innerHTML = data[i].title;
      imgGrabber.src = data[i].media[0].url;

      ul.appendChild(listItem);
      listItem.appendChild(imgGrabber);
    }


  });

So the issue arises when the fetch function comes upon the third object which contains no image. What do I need to do to make this loop grab only the images that exist, and skip empty objects? As it is now it's only loading the first three images and then stops.

I hope this makes sense let me know if I can improve this question.

Upvotes: 0

Views: 234

Answers (2)

Ori Drori
Ori Drori

Reputation: 192527

Add an if check to see if the media, and image url exist. The error is probably caused by trying to access url on the missing media[0].

if(data[i] && data[i].media && data[i].media[0] && data[i].media[0].url) {...}

The condition is evaluated from left to right, if data[i] is falsy (undefined in this case), it won't try accessing data[i].media, and so on.

Example:

fetch(url).then(function(response) {
    return response.json();
  })
  .then(function(data) {
    console.log(data);
    for (var i = 0; i < data.length; i++) {
      var listItem = document.createElement("li");
      var imgGrabber = document.createElement("img");

      listItem.innerHTML = data[i].title;

      if (data[i] && data[i].media && data[i].media[0] && data[i].media[0].url) {
        imgGrabber.src = data[i].media[0].url;
      }

      ul.appendChild(listItem);
      listItem.appendChild(imgGrabber);
    }

  });

Upvotes: 2

Dmitry Zaitsev
Dmitry Zaitsev

Reputation: 21

Maybe I'm wrong but I guess there is just exception - can't get property 'url' of undefined. So maybe just add condition?

if(data[i].media) { // or data[i].media[0] - depends on JSON structure
   imgGrabber.src = data[i].media[0].url;
   listItem.appendChild(imgGrabber);
}

Upvotes: 2

Related Questions