0

我想創建一個Google餅圖(https://jsfiddle.net/api/post/library/pure/)與我的數據聊天。 [{"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"}]從複雜數組和對象生成google api餅餡餅字符

我已經對數據進行分組相對於tag,這樣我可以生成餅圖與焦炭總量爲特定tag

我寫這樣的事情:

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]}); 


    } 
} 

但這= ngs越來越複雜。

所以請幫助我。

回答

0

嘗試這樣的:

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); 
    }