1

I'm working with charts.js to make a line chart out of a JSON file. To do that, I needed to create 3 arrays getting the values of the JSON with the method push:

var serieCasos = [];
var serieMortos = [];
var serieDatas = [];

$.getJSON('URL OF THE JSON', function(dados){

console.log(dados.length);
for(i=0; i<dados.length; i++){
    serieCasos.push(dados[i].infected);
}
for(i=0; i<dados.length; i++){
    serieMortos.push(dados[i].deceased);
}
for(i=0; i<dados.length; i++){
   var timeStamp = Date.parse(dados[i].lastUpdatedAtSource);
   var d = new Date(timeStamp);
    serieDatas.push(d.getDate() + "/" + d.getMonth());
}
});

2 of them are properly defined as numbers, and the other one has strings (these are the labels). When I tried to add the arrays into the charts.js code, it didn't recognize any of the 3 ones. On the other hand, when I created 2 simple arrays right inside the code, it worked properly in the chart:

var values = [1,5,3,4,5,6,7,8,9,10,11,1,2,13,14,15,16,17];
var labels = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p'];

In order to check the difference between the first and the second group of arrays, I showed them 5 in console.log. Then I noticed that google chrome really treats them differently, the push based ones are shown as:

> []
> []
> []

(In this case, values are shown when clicked in the side arrow, demonstrating that they are properly indexed in the array)

While the last 2 ones (hand coded ones) appear in the console like that:

> (16) ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p"]
> (18) [1, 5, 3, 4, 5, 6, 7, 8, 9, 10, 11, 1, 2, 13, 14, 15, 16, 17]

It is evident that I ended up with 2 different kinds of arrays. The difference between them might be the reason why the first group doesn't work, and the second one does. How can I format the first ones to act like the second group? And what exactly is the difference between them?

Alexander Nied
  • 12,804
  • 4
  • 25
  • 45
  • 1
    `console.log()` logs the state of the array/object at the moment of the `.log()` call. If you later click at the arrow to expand the array/object it shows the state of the array/object at that moment in time. – Andreas May 11 '20 at 14:15
  • 1
    See also [Weird behavior with objects & console.log](https://stackoverflow.com/q/23429203) – wOxxOm May 11 '20 at 14:16
  • After all, I have found the solution to my problem. It wasn't about any property of the array, but the time it was taking to load the data inside it. Since the getJSON is an asynchronous function by default, the chart was being loaded before it could get the data. So, I encapsulated the creation of the chart inside a function, and made it run as a call from the end of the getJSON function. – Pedro H. Souza May 11 '20 at 16:32

0 Answers0