Reputation: 49
I have an object and I am storing data as
{"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}
I'm trying to interpret this data into a chart, google api. using the following
data.addRows([
['Drugs', crimes.drugs],
['bicycle-theft', crimes.bicycle-theft],
]);
crimes.drugs works fine however crimes.bicycle-theft is throwing
Uncaught (in promise) ReferenceError: theft is not defined
at drawChart (crimes.js:126)
at <anonymous>
Upvotes: 1
Views: 60
Reputation: 61222
rather than hard-code the array,
use --> Object.keys
-- to build the rows...
Object.keys(objData).forEach(function (key) {
data.addRow([
key,
objData[key]
]);
});
see following working snippet...
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>
Upvotes: 0
Reputation: 193
There are two ways to access properties: dot notation and bracket notation.
When using dot notation, your property must be a valid JavaScript identifier.
When using bracket notation, the string provided does not have to be a valid identifier.
Here 'bicycle-theft' is not a valid identifier due to '-'.
Documentation : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors
Upvotes: 0
Reputation: 3795
You can't access properties like that way (crimes.bicycle-theft
) when have '-' symbol. You should write crimes["bicycle-theft"]
.
Upvotes: 0
Reputation: 222582
Since the property bicycle-theft
has a -
, you cannot access via dot operator
, try this way,
data.addRows([
['Drugs', crimes.drugs],
['bicycle-theft', crimes['bicycle-theft']],
]);
Upvotes: 4