2017-10-20 80 views
1

我有一個對象,我存儲數據的Javascript x被未定義對象/陣列

{"anti-social-behaviour":43,"burglary":24,"other-theft":29,"shoplifting":2,"vehicle-crime":27,"violent-crime":34,"criminal-damage-arson":17,"public-order":2,"drugs":1,"robbery":3,"other-crime":3,"bicycle-theft":1} 

我想要這個數據解釋成圖表,谷歌API。使用以下

data.addRows([ 
    ['Drugs', crimes.drugs], 
['bicycle-theft', crimes.bicycle-theft], 
]); 

crimes.drugs工作正常,但是crimes.bicycle盜竊被扔

Uncaught (in promise) ReferenceError: theft is not defined 
at drawChart (crimes.js:126) 
at <anonymous> 
+0

你能設置像「公共秩序」的價值觀嗎?如果是的話,這可能是圖表api將短劃線解釋爲負數的問題 –

回答

4

由於物業bicycle-theft有一個-,你無法通過dot operator訪問,試試這種方式,

data.addRows([ 
    ['Drugs', crimes.drugs], 
    ['bicycle-theft', crimes['bicycle-theft']], 
]); 
0

當有' - '符號時,您不能像這樣訪問屬性(crimes.bicycle-theft)。你應該寫crimes["bicycle-theft"]

0

,而不是硬編碼的陣列,
使用 - >Object.keys - 建行...

Object.keys(objData).forEach(function (key) { 
    data.addRow([ 
    key, 
    objData[key] 
    ]); 
}); 

看到下面的工作片段...

google.charts.load('current', { 
 
    packages: ['corechart'] 
 
}).then(function() { 
 

 
    var objData = {"anti-social-behaviour":43,"burglary":24,"other-theft":29,"shoplifting":2,"vehicle-crime":27,"violent-crime":34,"criminal-damage-arson":17,"public-order":2,"drugs":1,"robbery":3,"other-crime":3,"bicycle-theft":1}; 
 

 
    var data = new google.visualization.DataTable(); 
 
    data.addColumn('string', 'Crime'); 
 
    data.addColumn('number', 'Occurrences'); 
 

 
    Object.keys(objData).forEach(function (key) { 
 
    data.addRow([ 
 
     key, 
 
     objData[key] 
 
    ]); 
 
    }); 
 

 
    data.sort([{column: 1, desc: true}]); 
 

 
    var chart = new google.visualization.BarChart(document.getElementById('chart_div')); 
 
    chart.draw(data, { 
 
    chartArea: { 
 
     bottom: 24, 
 
     height: '100%', 
 
     left: 176, 
 
     right: 96, 
 
     top: 36, 
 
     width: '100%' 
 
    }, 
 
    height: 400, 
 
    legend: { 
 
     alignment: 'end', 
 
     position: 'top' 
 
    }, 
 
    title: 'Crime', 
 
    width: '100%' 
 
    }); 
 
});
<script src="https://www.gstatic.com/charts/loader.js"></script> 
 
<div id="chart_div"></div>