问题
The background for this question is I'm trying to access the selected cell from addListener in google visualization calendar. I could print the selected cell using JSON.stringify(chart.getSelection());
. It prints as [{"date":1468195200000,"row":0}]
.
My problem is to access this date object. I tried to access it as
var obj=JSON.stringify(chart.getSelection());
console.log('selected value '+obj.date);
But it displays as Undefined
. When I print the obj
it displays as [object, object]
If you need more information please let me know. Any suggestion would be appreciated.
回答1:
JSON.stringify() serializes a data object into a string. Just access the object directly.
var data = chart.getSelection()[0]; // assuming there is only ever one item in the selection array.
console.log(data.date)
回答2:
Try this:
var data = [{"date":1468195200000,"row":0}]
var rw = data[0].row;
var dt = new Date(data[0].date);
console.log(rw);
console.log(dt);
回答3:
careful when accessing the first array element directly when listening for the 'select'
event
chart.getSelection()[0]
the 'select'
event is fired, both when a selection is made, AND removed
so the above line will fail when the selection is removed
check the length
before accessing...
selection = chart.getSelection();
// check selection length
if (selection.length > 0) {
console.log(selection[0].date);
} else {
console.log('selection removed');
}
see following working snippet, select a date, then select again to remove the selection...
google.charts.load('current', {
callback: function () {
var dataTable = new google.visualization.DataTable();
dataTable.addColumn({ type: 'date', id: 'Date' });
dataTable.addColumn({ type: 'number', id :'Score' });
dataTable.addRows([
[ new Date(2016, 3, 13), 101 ],
[ new Date(2016, 3, 14), 102 ],
[ new Date(2016, 3, 15), 103 ],
[ new Date(2016, 3, 16), 104 ],
[ new Date(2016, 3, 17), 105 ]
]);
var chart = new google.visualization.Calendar(document.getElementById('chart_div'));
google.visualization.events.addListener(chart, 'select', function () {
var selection = chart.getSelection();
// check selection length
if (selection.length > 0) {
console.log(selection[0].date);
} else {
console.log('selection removed');
}
});
chart.draw(dataTable);
},
packages:["calendar"]
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
回答4:
This is an array of objects however there is only one object in this array (or so I think) so what you should do is console.log(obj[0].date);
instead!
来源:https://stackoverflow.com/questions/38319107/need-to-access-data-in-json-stringify-object