0

I have a json file:

[
    {"cat1":"A1","cat2":"B1","cat3":10},
    {"cat1":"A2","cat2":"B2","cat3":20},
    {"cat1":"A3","cat2":"B3","cat3":30}
]

And I need 2 array content:

["A1","A2","A3"]
[10,20,30]

My script should do the work:

var tab1 = [];
var tab2 = [];
var tab3 = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18];

$.getJSON("myjsonfile.json", function(json) {
    $.each( json, function( key, value ) {
        tab1[key] = value["cat1"];
        tab2.push(value["cat1"]);
    });
});

But it doesn't.

console.log(tab1[0]); // undefined
console.log(tab2[0]); // undefined
console.log(tab3[0]); // 0

I don't understand why

Macbernie
  • 1,303
  • 6
  • 24
  • 48
  • 1
    `$.getJSON` is asynchronous! Put the `console.log`s inside the callback at right after the `$.each`! – ibrahim mahrir Apr 16 '17 at 21:05
  • But how can I get my data in my 2 tables, outside of getJSON ? – Macbernie Apr 16 '17 at 21:06
  • 1
    *"outside of getJSON"* ... you don't...consume the data within the complete callback or promise chain. That is how asynchronous programming works – charlietfl Apr 16 '17 at 21:08
  • 1
    You wrap the code that uses the two arrays in a function and then call that function when `$.getJSON` finishes it's work (call the function right after `$.each` in the callback of `$.getJSON`)! Do you want me to post an example? – ibrahim mahrir Apr 16 '17 at 21:08
  • Indeed, thanks @ibrahim – Macbernie Apr 16 '17 at 21:14

0 Answers0