当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - generation google api pie char from complex array and object

问题描述:

I want to create a google pie (https://jsfiddle.net/api/post/library/pure/) chat with my data.[{"amt":"500","tag":"travel","date":"2015-11-23"},{"amt":"3750","tag":"rent","date":"2015-11-23"},{"amt":"500","tag":"food","date":"2015-11-23"},{"amt":"500","tag":"rent","date":"2015-11-23"},{"amt":"500","tag":"food","date":"2015-11-23"},{"amt":"3750","tag":"rent","date":"2015-11-23"},{"amt":"30","tag":"drinks","date":"2015-11-23"}]

I've to group the data with respect to tag so that i can generate pie char with total amount for a specific tag

I was writing something like this:

function genPiechart() { // generate piechart

if (localStorage.expArr) {

var expArr = JSON.parse(localStorage.getItem("expArr")),

tagObj = {},

i = expArr.length;

while (i--) {

var sHash = expArr[i].tag.toString();

if (typeof(tagObj[sHash]) == "undefined")

tagObj[sHash] = [];

tagObj[sHash].push(expArr[i].amt);

}

var amtArrArr = Object.keys(tagObj).map(function (key) {return tagObj[key]});

}

}

But this=ngs getting more complex.

So please help me on this.

网友答案:

Try with this:

jsFiddle

var myData = '[{"amt":"500","tag":"travel","date":"2015-11-23"},{"amt":"3750","tag":"rent","date":"2015-11-23"},{"amt":"500","tag":"food","date":"2015-11-23"},{"amt":"500","tag":"rent","date":"2015-11-23"},{"amt":"500","tag":"food","date":"2015-11-23"},{"amt":"3750","tag":"rent","date":"2015-11-23"},{"amt":"30","tag":"drinks","date":"2015-11-23"}]';

var myObj = generateTmpObj(JSON.parse(myData));

var tmpArray = [['Tag', 'Amount']];
    tmpArray = generate_array_for_DataTable(myObj);

google.setOnLoadCallback(drawChart(tmpArray));

function generateTmpObj(data) {
    var tmpObj = {};
    for(var i = 0; i < data.length; i++) {
       if (tmpObj[data[i].tag]) {
           tmpObj[data[i].tag] += parseInt(data[i].amt);
       } else {
           tmpObj[data[i].tag] = parseInt(data[i].amt);
       }
    }
    return tmpObj;
 }

 function generate_array_for_DataTable(data) {
    for (var prop in data) {
        tmpArray.push([prop, data[prop]]); 
    }
    return tmpArray;
 }

function drawChart(data) {
    var data = google.visualization.arrayToDataTable(data);

    var options = {
      title: 'My Pie Chart'
    };

    var chart = new google.visualization.PieChart(document.getElementById('piechart'));

    chart.draw(data, options);
  }
分享给朋友:
您可能感兴趣的文章:
随机阅读: