Chartjs-Dynamic array javascript

1👍

The valores var MUST BE a object instead of regular array type.So it should be something like this:

enter image description here

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>

    0👍

    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.

      Leave a comment