Reputation: 3
I'm trying to display the same data set with both jquery plugin DataTables and highcharts.js on my page. So that when I change the data both table and the chart will change as well. My data is something like this:
var data = [
{"itemName": "item1", "Jan": "4056479", "Feb": "3716377", "Mar": "6924148"},
{"itemName": "item2", "Jan": "3034448", "Feb": "930077", "Mar": "1210250"},
{"itemName": "item3", "Jan": "3938924", "Feb": "1624727", "Mar": "9626947"}
];
I can make it work with DataTables but despite days of work I could not convert it to a format Highcharts accepts. So far I can display the highcharts with following data set:
series: [
{
index: 0,
name: "Jan",
data: [
[data[0]["itemName"], parseFloat(data[0]["Jan"])],
[data[1]["itemName"], parseFloat(data[1]["Jan"])],
[data[2]["itemName"], parseFloat(data[2]["Jan"])],
]
},
{
index: 1,
name: "Feb",
data: [
[data[0]["itemName"], parseFloat(data[0]["Feb"])],
[data[1]["itemName"], parseFloat(data[1]["Feb"])],
[data[2]["itemName"], parseFloat(data[2]["Feb"])],
]
},
{
index: 1,
name: "Mar",
data: [
[data[0]["itemName"], parseFloat(data[0]["Mar"])],
[data[1]["itemName"], parseFloat(data[1]["Mar"])],
[data[2]["itemName"], parseFloat(data[2]["Mar"])],
]
}
]};
Can someone please give me a oneliner for-loop to convert the first set (based on itemName) to another (based on Months) that is accepted by Highcharts. I have pages of data. The above solution is not manageable.
Please see the jsfiddle here.
I wish I could mark both answers. Both solves my issue and I don't know which is technically better. Thanks for the prompt answers.
Upvotes: 0
Views: 594
Reputation: 5574
this will change the logic from name based to month based:
var data = [
{"itemName": "item1", "Jan": "4056479", "Feb": "3716377", "Mar": "6924148"},
{"itemName": "item2", "Jan": "3034448", "Feb": "930077", "Mar": "1210250"},
{"itemName": "item3", "Jan": "3938924", "Feb": "1624727", "Mar": "9626947"}
];
var months = ["Jan","Feb","Mar"] //and so on....
var series = [];
$.each(months,function(i,v){
var currentData = [];
$.each(data,function(k,l){
currentData.push([l.itemName,parseFloat(l[v])]);
});
series.push({index: i, name: v, data: currentData})
});
console.log(series);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
this is your fiddle edited: fiddle
Upvotes: 0
Reputation: 58870
SOLUTION
You can use the following function to filter out the data:
function filterData(data, key){
var result = [];
$.each(data, function(index, rcd){
result.push([rcd['itemName'], parseFloat(rcd[key])]);
});
return result;
}
Then for the HighCharts code you can just write:
{
index: 0,
name: "Jan",
data: filterData(data, "Jan")
}
DEMO
See this jsFiddle for code and demonstration.
Upvotes: 2