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

0๐Ÿ‘

โœ…

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')
   }
 ]
}

0๐Ÿ‘

You cant use Date as variable name since its a build in class. Also from my testing couldnt reference the vars inside the function. But the real problem with your code is that you push an array to the val array. This made it an array containing arrays. This is not supported. If you change your code to the sample below it will work

let date = [];
let val = [];

function ShowData(jsonObj) {
  var bases = jsonObj['Results'];
  date = [];
  val = [];

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

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

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

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'
                    }
            }
        }
    })

Leave a comment