2017-04-09 25 views
0

我試圖在我的localhost網頁上使用Google圖表顯示實時儀表板,從SQL Server表中收集數據。 我成功連接到數據庫並在localhost上顯示數據。解析JavaScript中的記錄集

我被困的地方在於,爲了在谷歌圖表中繪製餅圖,我需要從數據庫查詢中獲得4個整數,並使它們成爲一個百分比。 我的問題是解析DB響應,所以我可以單獨訪問每個整數。

我在localhost響應看起來是這樣的:

{ 
"recordsets": [ 
[ 
{ 
"Braking_Events": 1441, 
"Acceleration_Events": 2480, 
"Cornering_Events": 1270, 
"Speeding_Events": 2863 
} 
] 
], 
"recordset": [ 
{ 
"Braking_Events": 1441, 
"Acceleration_Events": 2480, 
"Cornering_Events": 1270, 
"Speeding_Events": 2863 
} 
], 
"output": {}, 
"rowsAffected": [ 
1 
] 
}  

我試圖訪問

"Braking_Events": 1441, 
"Acceleration_Events": 2480, 
"Cornering_Events": 1270, 
"Speeding_Events": 2863 

,並將其設置爲JavaScript的變量,它們操縱爲百分比,並將其貼到

function drawChart() { 

    var data = google.visualization.arrayToDataTable([ 
     ['Braking_Events', 1441], 
     ['Acceleration_Events',  2480], 
     ['Cornering_Events',  1270], 
     ['Speeding_Events', 22863] 
    ]); 

    var options = { 
     title: 'Safety Distribution' 
    }; 

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

    chart.draw(data, options); 
    } 
+0

@NinaScholz,不,我不需要兩個,不知道爲什麼他們出現因爲我在我的代碼發送'recordset'只有一次。 –

回答

0

你可以迭代對象的鍵和映射一個新的關鍵和價值部分數組。

var data = { recordsets: [[{ Braking_Events: 1441, Acceleration_Events: 2480, Cornering_Events: 1270, Speeding_Events: 2863 }]], recordset: [{ Braking_Events: 1441, Acceleration_Events: 2480, Cornering_Events: 1270, Speeding_Events: 2863 }], output: {}, rowsAffected: [1] }, 
 
    result = Object.keys(data.recordset[0]).map(function (k) { 
 
     return [k, data.recordset[0][k]]; 
 
    }); 
 

 

 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }