javascriptjqueryapidiscogs-api

Javascript jQuery calling on API to fill table but receiving undefined for a particular object call


So the problem I seem to be having is that when I populate my table the object discogsObjects.year populates my table consistently with "undefined" despite the fact that when I call it in devtools it returns values of years called from the API. My format is consistent with the code so I'm not sure what the problem could be...

Thank you!

var discogsObjects = {
    title: [],
    label: [],
    year: [],
};


$(".artistform").submit(function(event){
  event.preventDefault();

  var band = ($("#userInput").val());
  var url = "https://api.discogs.com/database/search?q=" + band + "&key=olnzRAzKsxiVlgocWNCH&secret=RPCwqvPXDmFkHHNzDePPKIcMsHRmNUIK"

  $.ajax({
    url: url,
    type: "GET",
    dataType: "json",
    success: (data)=> {
      console.log(data.results);



      for (i = 0; i<21; i++) {
        for(var key in data.results[i]){
          //if (key === "id") idArr.push(data.results[i][key]);
          if (key === "title")  discogsObjects.title.push(data.results[i][key]);
          if (key === "label") discogsObjects.label.push(data.results[i][key]);
          if (key === "year") discogsObjects.year.push(data.results[i][key]);
        }

          //$thead(.hidden).show()
          // $('#resultsHead').append('<tr><td>Year of Release</td><td>Artist Release</td><td>Record Label</td></tr>');

         $('#resultsTable').append('<tr><td>'+discogsObjects.title[i]+'</td><td>'+discogsObjects.year[i]+'</td><td>'+discogsObjects.label[0]+'</td></tr>');


      }
    }
  });
});

Solution

  • The first object returned in the "results" array is a description of the band which does not have a year attribute so the first iteration of your for loop doesn't populate the year array in the discogsObjects object and thus on every iteration thereafter undefined will be appended to the DOM because it's off by one.

    For example, using "Maroon 5" the first object returned will be:

    {  
        "thumb":"https://api-img.discogs.com/gcuqJ3Ni4_2F_F_35xU7anju50Q=/150x150/smart/filters:strip_icc():format(jpeg):mode_rgb():quality(40)/discogs-images/A-192151-1452146008-4372.jpeg.jpg",
        "title":"Maroon 5",
        "uri":"/artist/192151-Maroon-5",
        "resource_url":"https://api.discogs.com/artists/192151",
        "type":"artist",
        "id":192151
    }
    

    So your for loop won't find a key named "year", and discogsObject.year will be empty. Then you append discogsObject.year[i] when i = 0 which is undefined. Next, i is incremented and a year is found in the next object, pushing it onto the year array, but when appending it to the DOM you're trying to do discogsObject.year[i] when i = 1, but discogsObject.year.length = 1 so this is undefined.