EI-01
EI-01

Reputation: 1095

JSON format for google pie chart

Hello i have a json file that has data stored like this:

[{"cake": "cake1","order": 20},{"cake": "cake2","order": 34},{"cake": "cake3",
  "order": 11}, {"cake": "cake4","order": 11}, {"cake": "cake5", "order": 5}]

Now i want to represent the above data using google's pie chart but in order to do accomplish this, it needs to be in this format:

[ ['Cake', 'No of Orders'], ['cake1', 20],['cake2',34],
  ['cake3', 11],['cake4',11],['cake5',5] ]

google's chart documentation specifies that data should be passed like this:

var data = google.visualization.arrayToDataTable([
          ['Cake', 'No of Orders'],
          ['cake1', 20],
          ['cake2', 34],
          ['cake3',  11],
          ['cake4', 11],
          ['cake5', 5]
        ]);

Please how does one change the original format above into a list containing severals list in javascript. Much help would be appreciated.

Upvotes: 1

Views: 353

Answers (2)

malexanders
malexanders

Reputation: 3343

How about something like this? Try running this in jsbin.

var a = [{"cake": "cake1","order": 20},{"cake": "cake2","order": 34},{"cake": "cake3",
  "order": 11}, {"cake": "cake4","order": 11}, {"cake": "cake5", "order": 5}];

function cakeFormat(a){
  var first = [];
  console.log(a);
  // noprotect
  for(var i = 0; i < a.length; i++){
    for(var j in a[i]){
      first.push([j, a[i][j]]);
    }
  }

  var final = [["Cake", "No of Orders"]];

  for(var k = 0; k < (first.length - 1);){
    final.push([first[k][1], first[k+1][1]]);
    k = k + 2;
  }

  return final;
}

cakeFormat(a);

Upvotes: 0

nnnnnn
nnnnnn

Reputation: 150070

Perhaps using the array .map() method to change the format of the data, and then the array .unshift() method to insert the headings at the beginning of the new array:

var input = [{"cake": "cake1","order": 20},{"cake": "cake2","order": 34},
             {"cake": "cake3", "order": 11}, {"cake": "cake4","order": 11},
             {"cake": "cake5", "order": 5}];

var output = input.map(function(item) { return [item.cake, item.order]; });

output.unshift(["Cake", "No of Orders"]);

var data = google.visualization.arrayToDataTable(output);

Upvotes: 1

Related Questions