Chartjs-Unable to render two datasets from the controller in View

1👍

Issue & Concern

Because the below line overwrites the original data value.

var data = data.map(function (e) {
  return e.Value;
});

After the above line, now the data array was overwritten as an array of integers instead of an array of objects. Based on your sample response from API, the current value of data will be: [100].

var data2 = data.map(function (e) {
  return e.Age;
});

From the above line, it can’t find the Age property in the element. Hence the result of data2 will be: [undefined].

This is why the data2 is not rendered in the chart.


Solution

Create another variable for the data transformation to avoid overwriting the existing data value.

var dataset = data.map(function (e) {
  return e.Value;
});

var dataset2 = data.map(function (e) {
  return e.Age;
});

var config = {
  type: 'line',
  data: {
    labels: labels,
    datasets: [
      {
        label: 'Test',
        data: dataset,
        backgroundColor: 'rgba(0, 119, 204, 0.3)',
      },
      {
        label: 'Test',
        data: dataset2,
        backgroundColor: 'rgba(242, 204, 143, 1)',
      },
    ],

  },
};

Demo @ StackBlitz

Leave a comment