3

here i have data like this,

var dataArray = '[{"name":"books","value":43},{"name":"DVDs","value":99},{"name":"Magazines","value":37},{"name":"eBooks","value":88},{"name":"Other awesome things","value":67}]';

i want to construct this chart using this data dynamically, means my json will be large in actual project which will come from database.

here is jsfiddle for my desired chart (dynamically for my case):http://jsfiddle.net/artefactory/m4on9L4p/

//canvasJS example - doughnut chart showing collection breakdown.   

var dataArray = '[{"name":"books","value":43},{"name":"DVDs","value":99},{"name":"Magazines","value":37},{"name":"eBooks","value":88},{"name":"Other awesome things","value":67}]';

window.onload = function () {
    var chart = new CanvasJS.Chart("chartContainer",
    {
      title:{
        text: "What's in our collection"
      },
      data: [
      {
       type: "doughnut",
        // how to substitute above array here
       dataPoints: [
       {  y: 53.37, indexLabel: "Books" },
       {  y: 35.0, indexLabel: "DVDs" },
       {  y: 7, indexLabel: "Magazines" },
       {  y: 2, indexLabel: "eBooks" },
       {  y: 5, indexLabel: "Other awesome things" }
       ]
     }
     ]
   });

    chart.render();
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/canvasjs/1.4.1/canvas.min.js"></script>
 <div id="chartContainer" style="height: 300px; width: 100%;">  </div>

i want to build this

dataPoints: [
           {  y: 53.37, indexLabel: "Books" },
           {  y: 35.0, indexLabel: "DVDs" },
           {  y: 7, indexLabel: "Magazines" },
           {  y: 2, indexLabel: "eBooks" },
           {  y: 5, indexLabel: "Other awesome things" }
           ]

dynamically with my json. how can i do it?

Question: instead of using hardcoded value i want to use json to build graph?

3 Answers 3

4

The solution using JSON.parse() and Array.prototype.map() functions:

...
dataPoints:  JSON.parse(dataArray).map(function (o) {
    return {y: o.value, indexLabel: o.name};
})
...
Sign up to request clarification or add additional context in comments.

Comments

0

How are the values 53.37, 35.0 being derived? Is there a mathematical formula for their derivation?

If you just mapping "names" to indexLabel and "value" to x, then this piece of code should work.

var desiredObj = x.map(function(currentElement) {return {x: currentElement.value, indexLabel: currentElement.name}});

1 Comment

ha ha @Dinesh Verma, what you are asking man, what i want dataPoints:[] to be replaced by my json thats it
0

You can use the jQuery map function like this :

var myNewDataArray = $.map(dataArray,function(a,b){
    return {
        y : a.value,
        indexLabel : a.name
    }
});

Comments

Your Answer

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