Reputation: 266
I am collecting data from an API.
Comes in JSON format:
[{'time':'08h00','magnitude':25, 'temper':12.6},{'time':'09h00','magnitude':39, 'temper': 5.3}]
Making my chart:
const ctx = document.getElementById('chart').getContext('2d');
const chart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
label: "Line Graph",
data: [],
parsing: {
xAxisKey: 'time',
yAxisKey: 'temper'
},
borderColor: function(context) {
var index = context.dataIndex;
var value = context.dataset.data[index];
console.log(value);
return value > 10 ? 'red' : 'green';
},
}]
},
options: {
scales: {
x: {
type: 'time',
time: {
unit: 'day',
},
},
},
responsive: 'true',
}
});
Then I populate it:
function addData(chart, data) {
for (x in data) {
chart.data.datasets[0].data.push(data[x]);
}
chart.update();
}
$.getJSON("https://8.0.0.85/last_48_hours", function (data) {
addData(chart, data)
});
My issue is with this, which comes right out of the docs:
borderColor: function(context) {
var index = context.dataIndex;
var value = context.dataset.data[index];
console.log(value);
return value > 10 ? 'red' : 'green';
},
because value
is the whole Object {'time':'08h00','magnitude':25, 'temper':12.6}
var value = context.dataset.data[index].temper;
and
var value = context.dataset.data[index]['temper'];
and all manner of do not work. How can I reference value['temper']
?
Upvotes: 2
Views: 1857
Reputation: 26150
I can't tell you why it's not working but you can change the following line inside the the scriptable function.
from:
var value = context.dataset.data[index].temper;
to:
var value = context.dataset.data[index]?.temper;
The problem is that context.dataset.data[index]
sometimes results in undefined
.
Please take a look at your amended code below:
new Chart('myChart', {
type: 'line',
data: {
datasets: [{
label: "Line Graph",
data: [{
'time': '08h00',
'magnitude': 25,
'temper': 12.6
}, {
'time': '09h00',
'magnitude': 39,
'temper': 5.3
}],
parsing: {
xAxisKey: 'time',
yAxisKey: 'temper'
},
borderColor: function(context) {
var index = context.dataIndex;
var value = context.dataset.data[index]?.temper;
return value > 10 ? 'red' : 'green';
}
}]
},
options: {
scales: {
x: {
type: 'time',
time: {
parser: 'HH\hmm',
unit: 'day',
},
},
},
responsive: 'true'
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.5.1/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<canvas id="myChart"></canvas>
Upvotes: 4