0

http://codepen.io/noczesc/pen/ZWppJQ?

function codeToName(data) {
    for (var i = 0; i < data.country.borders.length; i++) {
        $.getJSON("https://restcountries.eu/rest/v1/alpha?codes=" + data.country.borders[i], function(json) {
            data.country.borders[i] = json[0].name;
            console.log(json[0].name);
        });
    }
};

I'm getting an array of country codes which are supposed to be changed to their full representations in English via the codeToName loop and an API, but it only appends a random name to the end of the array. To get a console.log of it, click on the <body>. It's located in JSONextract.country.borders. The country names grabbed via API are correct (logged in console also), but they don't get assigned to the variables inside my object. How can I solve this issue?

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
macbem
  • 1,180
  • 2
  • 9
  • 21
  • The Ajax calls are asynchronous, which means the entire loop completes before the success callbacks get called, which means that by then the variable `i` is equal to data.country.borders.length. For solutions, see the (many) other questions about doing asynchronous operations in a loop. – nnnnnn Mar 13 '16 at 11:53
  • Thanks for the explanation, I already fixed this issue. I will research this later. – macbem Mar 13 '16 at 17:28

1 Answers1

0

for does not work, you should use $.each

function codeToName(data) {
  $.each(data.country.borders, function(index,item){
      $.getJSON("https://restcountries.eu/rest/v1/alpha?codes=" + item, function(json) {
          data.country.borders[index] = json[0].name;
          console.log(json[0].name);
      });
  });
};
Shayan
  • 956
  • 9
  • 20
  • It would need to be data.country.borders[index] = json[0].name, because `item` is (in this case) just a string, not a reference back to the array element. And it's being assigned a string value. – nnnnnn Mar 13 '16 at 11:57
  • @nnnnnn yeah your right – Shayan Mar 13 '16 at 11:59
  • Still, using $.each() is a very convenient way to create a closure for each iteration. – nnnnnn Mar 13 '16 at 12:01
  • Thanks for the tip, I managed to fix my code and it's working now. – macbem Mar 13 '16 at 17:29