Skip to content
Advertisement

How to use a Data Array within a Chart JS dataset?

I have the following JSON, that I want to insert a chart using Chart JS:

{"Results":[{"Data":"25/02/2021","Valor":18},{"Data":"24/02/2021","Valor":2993},{"Data":"23/02/2021","Valor":1936},{"Data":"22/02/2021","Valor":1844},{"Data":"21/02/2021","Valor":1114},{"Data":"20/02/2021","Valor":1060},{"Data":"19/02/2021","Valor":1134}]}

And I created a function to load this JSON into an Array:

function ShowData(jsonObj) {
  var bases = jsonObj['Results'];
  var Date = [];
  var Val = [];

  for (var i = bases.length-1; i >= 0; i--) {

    Date.push([bases[i].Data]);

    Val.push([bases[i].Valor]);
  }
}

When I load this Array into the Chart, As below:

var chartGraph = new Chart(ctx,{
        type:'line',
        data:{
            labels: Date,
            datasets: [
                {
                    label: "Lbl Name",
                    data: Val,
                    borderWidth: 6,
                    borderColor: 'rgba(77,166,253, 0.85)',
                    backgroundColor: 'transparent'
                }
            ]
        },
        options: {
            title: {
                display: true,
                fontSize: 20,
                text: 'Chart Name'
            },

            legend: {
                display: true,
                position: 'right',
                labels: {
                        fontColor: '#666'
                    }
            }
        }
    })

No information on “datasets” appears to me, only the “label”, what is the mistake I am making?

Graphic Image

Advertisement

Answer

Try to split series and data, something like:

function splitData(type) {
  return json.Results.map(v => v[type]);
}

// your Chart.js config
data: {
 labels: splitData('Date'),
 datasets: [
   {
     // ...otherProps,
     data: splitData('Valor')
   }
 ]
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement