Reputation: 1546
To display some data from my database I would like to use this nice graph library (Angular Chart).
The format of the data bugs me a little, I have some nice JSON data coming from my database in this format:
{ "data": [
{
"meting": "749",
"bericht": "408",
"plant": "01",
"timestamp": "2016-03-18T09:40:58.977051"
},
{
"meting": "775",
"bericht": "177",
"plant": "01",
"timestamp": "2016-03-18T07:35:59.007320"
}
]
};
But for these charts I need to put it in arrays like this:
$scope.labels = ["January", "February", "March", "April", "May", "June", "July"];
$scope.series = ['Series A', 'Series B'];
$scope.data = [
[65, 59, 80, 81, 56, 55, 40],
[28, 48, 40, 19, 86, 27, 90]
];
I believe this is a terrible data format but I'm willing to use this library anyway.
Now how do I get from my data to these crazy ugly arrays?
My current code is this but I'm sure there is a much better way of doing it and I can't get the $scope.data
right so now it's hard coded.
// data test
$scope.zdata =
{ "data": [
{
"meting": "749",
"bericht": "408",
"plant": "01",
"timestamp": "2016-03-18T09:40:58.977051"
},
{
"meting": "775",
"bericht": "177",
"plant": "01",
"timestamp": "2016-03-18T07:35:59.007320"
}
]
};
$scope.labels = [];
$scope.series = [];
$scope.data = [];
var datalength = $scope.zdata.data.length;
for (var i = 0; i < datalength; i++) {
$scope.labels.push($scope.zdata.data[i].timestamp);
}
for (var i = 0; i < datalength; i++) {
$scope.series.push($scope.zdata.data[i].plant);
}
$scope.data = [
[65, 59, 80, 81, 56, 55, 40]
];
Upvotes: 0
Views: 4224
Reputation: 4230
The data array is a multi dimensional array because it it possible to have multiple lines or bars. You may find it ugly but it is pretty common programming technique ;)
If you have only one series you just need to set the data to $scope.data = [[]];
and push the elements to the first inner array (index 0).
You also don't need to loop multiple times you can do it in one loop.
$scope.labels = [];
$scope.series = [];
$scope.data = [[]];
for (var i = 0, l = $scope.zdata.data.length; i < l; i++) {
$scope.labels.push($scope.zdata.data[i].timestamp);
$scope.series.push($scope.zdata.data[i].plant);
$scope.data[0].push($scope.zdata.data[i].meting); // assuming this is what you want to use as the values for the chart points
}
Instead of a for loop you could use forEach
instead:
$scope.labels = [];
$scope.series = [];
$scope.data = [[]];
$scope.zdata.data.forEach(function (zdata) {
$scope.labels.push(zdata.timestamp);
$scope.series.push(zdata.plant);
$scope.data[0].push(zdata.meting);
});
Upvotes: 2
Reputation: 108
I'm ussing charts.js too and my code is the same like yours... I chose this way because I have large amounts of data in my objects.
Upvotes: 1