0

What I'm trying to do is build an array from a JSON response. I'm not sure what I'm doing wrong. The array is somehow built but I can't access the elements like active_team_members[0];

Any idea on what I'm doing wrong?

Thanks.

var active_team_members = getJsonUsers(); 
console.log(active_team_members[0]); // this returns "undefined"

var x_active_team_members = [1,2,3,4,5];
console.log(x_active_team_members[0]); // this works

console.log(active_team_members); //returns some kind of array? If you check your browser console you can see the array but it differs from the one below

console.log(x_active_team_members); //this is a normal array


function getJsonUsers() {

 var members = [];

 $.getJSON( "http://www.json-generator.com/api/json/get/bZjdjoFLvS?indent=2", function( data ) {

  $.each( data, function( key, val ) {
   $.each( val, function( k, v ) {

    members.push(parseInt(v.user.uid));

   });
  });

 });  

 return members;

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
Mihai Chiriac
  • 133
  • 2
  • 8
  • I literally had just finished typing out an sample + explanation when @brk closed this >.< ... sry. But yeah, `getJSON` is an asynchronous function so you need to handle it's response in the function callback. Also you have an unneeded `$.each`, you just want to `$.each` over `data.users` and get `val.user.uid`. – dgeare Jul 06 '18 at 15:44
  • Thanks @dgeare . Yep, this was the problem. I used $.ajax with "async: false" instead of $.getJSON and it worked. – Mihai Chiriac Jul 06 '18 at 15:51
  • @dgeare I am sorry for that – brk Jul 06 '18 at 15:51
  • @MihaiChiriac you're going to want to look into how to structure your code using the asynchronous methods provided via `callbacks`, `complete` functions, `always` etc. JavaScript is single threaded and `async:false` hangs the main thread negating all user input; including clicks and scroll events. `async:false` is a very strong anti-pattern and probably never should have been implemented in jQuery (I think it's actually deprecated now). It might not seem like a problem when you develop on your desktop, but people on 3g networks _will_ notice the pain. Just FYI. – dgeare Jul 06 '18 at 16:05
  • @brk no worries. It happens ¯\_(ツ)_/¯ – dgeare Jul 06 '18 at 16:06

0 Answers0