0

I am having an issue with loops and the use of the $.getJSON() method in jQuery. I am trying to map the finalWords array and for each word, I want to make an API call to get the definition of each.

Once I get the data back from the API call, I want to loop through the definitions with another map. However, the second parameter, "ind" keeps logging as "0" and doesn't increment like I think it should. Basically this is a problem because I am giving each an id of "clue+ind" and I want to change the css using the id.

I am pretty new to this so I am not sure if it is something I am doing wrong with the loops inside the $.getJSON or something else. Any suggestions? Thanks!

var finalWords = ["smart", "jolly", "goofy", "clever", "graceful", "kind", "happy"]

finalWords.map(function(i, index){

  // loops thru finalWords array and then makes an API call to Wordnik
  $.getJSON(`http://api.wordnik.com:80/v4/word.json/${i}/definitions?limit=1&includeRelated=true&sourceDictionaries=all&useCanonical=true&includeTags=false&api_key=...`, function(data){

    data.map(function(j, ind){ 

   // loop thru data returned from API and give it a Bootstrap "col-md-8" class
      console.log(ind); //this logs 0 every time...
      $("#clues").append(`<div class="col-md-8" id="clue${ind+1}">${j.text}</div>`).css({"font-size":"1em"});
       $(`#clue${ind+1}`).css({"border":"1px solid black"}); //...so only the first div "#clue1" is given the border property
      $("#clues").append(`<div class="col-md-2" id="wordLength${ind+1}">${i.length} letters</div>`)
    });
  });

});

lnamba
  • 1,681
  • 3
  • 18
  • 26
  • Look at http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example?rq=1 and http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Heretic Monkey Mar 14 '17 at 16:52
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Heretic Monkey Mar 15 '17 at 17:55

0 Answers0