Search code examples
javascriptangularjsjsonangular-chartchart.js

Charts in Angular js with JSON Object


I am trying to implement chart representation in angular js.

http://jtblin.github.io/angular-chart.js/

I was able to implement simple charts but I have a below data to be represented. It is in JSON format. I need help on how to convert JSON to arrays to be represented as charts. Below is JSON

[{"value": {"DE":2,"NP":20,"BD":28,"TW":1},
  "end_time":"2016-07-05T07:00:00+0000"},
 {"value":{"DE":5,"NP":11,"BD":22,"BE":2,"FJ":2},
  "end_time":"2016-07-06T07:00:00+0000"},
 {"value":{"DE":5,"NP":24,"BD":29},
  "end_time":"2016-07-07T07:00:00+0000"}]

I am trying to convert it to the format

$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 understand that I need to iterate over my JSON object and create arrays.

My question is I have different labels in each of the JSON object. How do I convert it create an array with all the labels in each of the value and still maintain the order of counts.Like below

$scope.labels = ["DE", "NP", "BD", "TW", "BE", "FJ"];
$scope.series = ["2016-07-05T07:00:00+0000","2016-07-06T07:00:00+0000","2016-07-07T07:00:00+0000"]
$scope.data = [ [2,20,28,1,0,0],
                [5,11,22,0,2,2],
                [5,24,29]
              ]

If this can be better achieved using different libraries or charts in angularjs please do suggest


Solution

  • Have you even attempted something? You didn't show any solution. Anyway, here's a possible implementation

    var source = [
      {"value": {"DE":2,"NP":20,"BD":28,"TW":1},
      "end_time":"2016-07-05T07:00:00+0000"},
      {"value":{"DE":5,"NP":11,"BD":22,"BE":2,"FJ":2},
      "end_time":"2016-07-06T07:00:00+0000"},
      {"value":{"DE":5,"NP":24,"BD":29},
      "end_time":"2016-07-07T07:00:00+0000"}
    ]
    var $scope = {};
    $scope.labels = [];
    $scope.data = [];
    $scope.series = [];
    
    
    source.forEach(function(item){
      $scope.series.push(item.end_time)
    
      var values = []
      Object.keys(item.value).forEach(function(key) {
        if ($scope.labels.indexOf(key) === -1) {
         $scope.labels.push(key)
        }
        values.push(item.value[key])
      })
      $scope.data.push(values)
    })
    console.log($scope)