How to transfer json data in highcharts series?

I have the following json array that is created at runtime. Therefore, the number of name / data pairs changes.

`var sales = { "SalesData" : [ { "name" : "AllProducts|Canada", "data" :[44936.0,50752.0] }, { "name" : "AllProducts|Mexico", "data" : [200679.0,226838.0] }, { "name" : "AllProducts|USA", "data" : [288993.0,289126.0] } ]} ` 

I want to transfer this data in a series in highcharts.

This is how I do it now.

 series: [ {name:sales.SalesData[0].name,data:sales.SalesData[0].data}, {name:sales.SalesData[1].name,data:sales.SalesData[1].data}, {name:sales.SalesData[2].name,data:sales.SalesData[2].data} ] 

But if the number of elements in the array changes, this will not work. How to solve this problem? The demo code will help me.

I refereed the following questions, but I could not solve the problem.

Dynamic Adding to Highcharts

Highcharts Series Dataset

+6
source share
2 answers

I solved the problem

Changed json array as follows:

 var sales = [ { "name" : "AllProducts123|Canada", "data" :[44936.0,50752.0] }, { "name" : "AllProducts|Mexico", "data" : [200679.0,226838.0] }, { "name" : "AllProducts|USA", "data" : [288993.0,289126.0] } ] 

Now pass it directly to the series in highcharts.

  series:sales 

Done !!!!!

+3
source

Instead of manually creating the series array, you could iterate over the data in the sales variable and build the array. So, how many elements in the sales.SalesData array sales.SalesData all elements be present in the series array

 var series = [], salesData= sales.SalesData; for (var i=0 i< salesData.length; i++) { series.push({"name" : key, "data" : sales[key]}) } 

This constructed series array is part of the object that you must pass as an argument to the highcharts method.

 var chartdata = { chart: {type: 'column'}, title: {text: 'Sales Data'}, xAxis: { categories: ['Category 1','Category 2'] }, yAxis: { min: 0, title: {text: 'Sales'} }, series : [] } chartdata.series = series; $('#chart').highcharts(chartdata); 

where #chart is the container in which you want to display the chart.

You can also refer to the scripts that are available on your demo pages for each type of chart to learn more about how to display a specific type of chart.

+4
source

Source: https://habr.com/ru/post/985161/


All Articles