0

I am using Highcharts to create multiple bars on a chart and I get the data from an Ajax call.

What I encounter is linked to the format of the array I get.

What I am doing to create the array is :

elements = [];

// AJAX request here ($.getJSON(...))

    $.each(data, function(key, value) {
        elements.push(value.item1);
    }

// End of $.getJSON

When using this method, Highcharts does not work properly, I know I can add the data another way but I would still like to solve this problem.

Here is what happens when I console.log(elements) :

Array []
​
0: 0
​
1: 0
​
2: 0
​
3: 0
​
4: 0
​
5: 5
​
6: 0
​
length: 7
​
<prototype>: Array []

I can get the structure I want by writing var elements = [0, 0, 0, 0, 5, 0];

When I console.log(elements) I get this structure :

Array(6) [ 0, 0, 0, 0, 5, 0 ]
​
0: 0
​
1: 0
​
2: 0
​
3: 0
​
4: 5
​
5: 0
​
length: 6
​
<prototype>: Array []

To me both arrays are similar but there's a difference on the first line of the console.log().

I don't really understand what is causing this.

EDIT: After the Ajax and the $.each, I create the chart, but when using an array created with

elements.push()

the chart is not created.

My problem does not come from the fact that console.log displays different things, it comes from the fact that Highcharts does not "understand" the array I am giving it.

HectorB
  • 113
  • 6
  • Have you verified that `value.item1` contains the value you expect it to contain? – Vini Dec 09 '22 at 08:06
  • In the first example, you're probably logging the array before it is populated. When you expand the array, it will show the updated array every time because it keeps a reference – adiga Dec 09 '22 at 08:08
  • @Vini yes, basically the first console.log is the data I get from the ajax call, the second one is created by me by writing manually the data I get from the AJAX to debug, so the data is the same. – HectorB Dec 09 '22 at 08:16
  • As @adiga mentioned, you are trying to print the array before it is populated. You can try populating the array and process it in the `.done` handler/callback. Created a sample jsFiddle here https://jsfiddle.net/r6qapug5/2/ – Vini Dec 09 '22 at 09:13
  • Hi @HectorB, It would be good if you could reproduce the problem in some live example. However, you probably try to create a chart before async data is received. You need to create a chart or update it after the async operation. Please check this simple demo: http://jsfiddle.net/BlackLabel/xb3ksgfh/ – ppotaczek Dec 09 '22 at 10:03

0 Answers0