Flint Flint - 27 days ago 6
HTML Question

C3 chart json data formatting in Javascript

I am using C3 donut chart in a simple html page. When I use the following code the chart loads without error:

json : [{"Total Participants":4825},{"Male":3019},{"Female":1806},],
keys : {
value : ['Total Participants', 'Male', 'Female' ],
}


But I have to build input for both 'json' and 'keys' using javascript so that it is not static. Note that I dont want to use ajax here. I just want to build the input

[{"Total Participants":4825},{"Male":3019},{"Female":1806},]


and

['Total Participants', 'Male', 'Female' ]


using javascript. Here is the code I tried which did not work.

var keysChart = '[';
var chartJsonData = '[';

for (var i = 0; i < data.length; i++) {
keysChart += data[i].title;
if(i < data.length - 1) keysChart += ',';
chartJsonData += '{';
chartJsonData += data[i].title;
chartJsonData += ':';
chartJsonData += data[i].value;
chartJsonData += '}';
chartJsonData += ','
}

chartJsonData += ']';
keysChart += ']';


The output of the above code looks similar to what I want but its not working. I believe there may be some formatting issue.

I am using the generated data in the following way:

json : chartJsonData,
keys : {
value : keysChart,
}


Having the following error in the console:

Uncaught TypeError: a.forEach is not a function

Answer
var arrData = [];
var keysForChart = [];

var jsJsonObj = new Object();

for (var it = 0; it < data.length; it++) { // data from an external json file. 
   keysForChart.push(data[it].title);
   jsJsonObj[data[it].title] = data[it].value;
}

arrData.push(jsJsonObj);

Then generated the chart using the following code

c3.generate({
  bindto : '#chart',
  data : {
    json : arrData,
    keys : {
      value : keysForChart
    },
    type : 'bar'
  },
  .....
});
Comments