Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops For Loops

Juliette Tworsey
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Juliette Tworsey
Front End Web Development Techdegree Graduate 32,425 Points

jQuery/JS for loop Treehouse Badges JSON

Hi,

I have set up a Javascript file in a project that I am working on to retrieve my badges here on Treehouse. My question is how should I approach setting up a for loop so that I can show only my latest 20 badges. I'm stumped. Thanks to anyone that can help. Here is the code (that works) that I have so far:

$(document).ready(function(){
var treehouseAPI = "https://teamtreehouse.com/juliettetworsey.json";
  $('.badges').html('<h1 style="font-family: Poller One;">Loading....</h1>');
 var  treehouseOptions = { format: "json" };


      function displayBadges(data){
      var badgesHTML = "";
      badgesHTML += '<h1>Points on Treehouse' + " " + data.points.total +'</h1>';
      badgesHTML += '<ul>';
      $.each(data.badges, function(j, badge){
      badgesHTML += '<li class = "bquery">';
      badgesHTML += '<img style="width: 120px; height: 120px; " src="' + badge.icon_url + '"></a></li>';
      });
      badgesHTML += '</ul>';
      $('.badges').html(badgesHTML);
    }
    $.getJSON(treehouseAPI,treehouseOptions, displayBadges);
  });

1 Answer

Aaron Kaye
Aaron Kaye
10,948 Points

Here is one possible solution. If you modify this line in your code:

$.each(data.badges.slice(data.badges.length-20,data.badges.length), function(j, badge){

Notice how I added the slice method to the data.badges, the slice method takes a start and an end. Since the JSON starts with your earliest badge, we needed to find the length of the badges array and take from the 20th to last till the last. Hope that made sense!