I'm with a simple doubt in javascript.
I have a array load by server:
var dados = [{'ano':2016,'id':1,'mes':1,'valor':87},{'ano':2016,'id':2,'mes':2,'valor':17},{'ano':2016,'id':3,'mes':3,'valor':26}]
After I get the values that I need:
var valores = new Array();
for( var i=0; i < dados.length; i++) {
valores.push(dados[i].valor);
}
Now is the doubt. How can I load the values to Chart.js?
var lineChartData = {
datasets : [{
//ommited others configs..
data : valores (I would like load de values of valores here)
}]}
felipsmartins
13.6k4 gold badges51 silver badges58 bronze badges
asked Apr 23, 2016 at 16:47
Alberto Rocha
211 silver badge4 bronze badges
2 Answers 2
The valores var MUST BE a object instead of regular array type.So it should be something like this:
Look at the below code:
<html>
<body>
<canvas id='myChart'></canvas>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js'></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.1.1/Chart.js"></script>
<script>
var dados = [
{'ano':2016,'id':1,'mes':1,'valor':87},
{'ano':2016,'id':2,'mes':2,'valor':17},
{'ano':2016,'id':3,'mes':3,'valor':26}
];
var valores = {
// labels like month (mes/mês - I noticed you're a portuguese speaker)
labels: [],
datasets: [
{label: null, data: []}
//more items here whether you want
]
};
for (var index in dados) {
currData = dados[index];
valores.labels.push('Mês ' + currData['mes']);
valores.datasets[0]['data'].push(currData['valor']);
}
var ctx = $("#myChart").get(0).getContext("2d");
var myLineChart = new Chart(ctx).Line(valores);
</script>
</body>
</html>
answered Apr 23, 2016 at 17:38
felipsmartins
13.6k4 gold badges51 silver badges58 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
No, a chart will take an array as an input with objects within it. Datasets cannot be an array, insted it should be a collection of objects.
your JSON data should be like
var lineChartData = {
data : [{
'valor':87
},{
'valor':22
}]
}
Now Just see that you correct pass the above JSON to the chart. Hope this will solve your problem.
answered Apr 23, 2016 at 16:58
Punith Mithra
6285 silver badges9 bronze badges
1 Comment
Alberto Rocha
Thanks, but the docs show that dataset can be a array. link
lang-js
valoresdata to be presented in, String, Array, Oblect..?datasets: [{data: valores}]is not supposed to do it correctly? Você já não está passando/atribuindovaloresadata?