Search code examples
jsonrestkendo-uikendo-datavizkendo-chart

Kendo UI Chart - Visualize count of returned JSON fields


I want to display the counts of specific retrieved fields in my pie/donut chart. I'm retrieving data via REST and the result is in json format. The source is a list repeating values:

Example: In the following list, I'd like to get a present the number (count) of completed responses; perhaps in a second chart present the breakdown of responses by location.

var userResponse  = [
      {     User:  "Bob Smith", Status: "Completed", Location: "USA" },
      {     User:  "Jim Smith", Status: "In-Progress", Location: "USA" }, 
     {     User:  "Jane Smith", Status: "Completed", Location: "USA" },
     {     User:  "Bill Smith", Status: "Completed", Location: "Japan" },
     {     User:  "Kate Smith", Status: "In-Progress", Location: "Japan" },
     {     User:  "Sam Smith", Status: "In-Progress", Location: "USA" },
 ]

My Initialization currently looks like this:

$('#targetChart').kendoChart({

    dataSource: {

        data: data.d.results,

        group: {

            field: "Location",
        },

    },

    seriesDefaults: {

        type: "donut",

    },

    series: [{

        field: 'Id',

        categoryField: 'Location',
    }],

});

Solution

  • You can easily transform the data. Read it into a DataSource object grouping by location and filtering for completed only. Then fetch the data and create an array of the counts for each location:

    var pieData = [];
    
    var respDS = new kendo.data.DataSource({
      data: userResponse,
      group: {
        field: "Location",
      },
      filter: { 
        field: "Status", 
        operator: "eq", 
        value: "Completed" },
    });
      
    respDS.fetch(function(){
      var view = respDS.view();
      for (var i=0; i<view.length; i++){
        var item = {};
        item.Location = view[i].value;
        item.Count = view[i].items.length;
        pieData.push(item);
      }      
    });
    

    You end up with:

    [
      {Location: "Japan", Count: 1},
      {Location: "USA", Count: 2},
    ]
    

    This can then be bound to a pie/donut.

    DEMO