1

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
5
  • Maybe it's a problem with comma after array called value Commented Jul 22, 2016 at 7:46
  • what is data[i].title ? or you want to use tableData[i].title ? Commented Jul 22, 2016 at 7:50
  • @AlexandruMihai Sorry for the confusion. Edited the post. Titles are ['Total Participants', 'Male', 'Female' ]. Values are [4825, 3019, 1806] Commented Jul 22, 2016 at 7:56
  • Removed. But still get the same exception @AlexandruMihai Commented Jul 22, 2016 at 8:01
  • please show me how looks data Commented Jul 22, 2016 at 8:04

1 Answer 1

1
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'
  },
  .....
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.