-1

i am new to chartjs i want charts using chartjs here i have json so i want to display like this that is Sample Image is this so please help me and json array is

[
      {
        "ChartGroupName": "Group-A",
        "Apple": 45,
        "Banana": 37,
        "Kiwi_fruit": 60,
        "Blueberry": 70,
        "Orange": 46,
        "Grape_Fruit": 33
      },
      {
        "ChartGroupName": "Group-B",
        "Apple": 50,
        "Banana": 35,
        "Kiwi_fruit": 70,
        "Blueberry": 65,
        "Orange": 40,
        "Grape_Fruit": 53
      },
      {
        "ChartGroupName": "Group-C",
        "Apple": 55,
        "Banana": 39,
        "Kiwi_fruit": 80,
        "Blueberry": 75,
        "Orange": 52,
        "Grape_Fruit": 73
      }
    ]
Farhat Zaman
  • 1,339
  • 10
  • 20

1 Answers1

0

Provided your JSON data is present in an array named data, you could generate labels and datasets as follows:

const labels = Object.keys(data[0]).slice(1).map(l => l.replace('_', ' '));
const datasets = data.map((o, i) => ({
    label: o[0],
    data: Object.values(o).slice(1),
    backgroundColor: colors[i]
  })
);

Please take a look at below runnable code snippet that illustrates how it works.

const data = [
  {
    "ChartGroupName": "Group-A",
    "Apple": 45,
    "Banana": 37,
    "Kiwi_fruit": 60,
    "Blueberry": 70,
    "Orange": 46,
    "Grape_Fruit": 33
  },
  {
    "ChartGroupName": "Group-B",
    "Apple": 50,
    "Banana": 35,
    "Kiwi_fruit": 70,
    "Blueberry": 65,
    "Orange": 40,
    "Grape_Fruit": 53
  },
  {
    "ChartGroupName": "Group-C",
    "Apple": 55,
    "Banana": 39,
    "Kiwi_fruit": 80,
    "Blueberry": 75,
    "Orange": 52,
    "Grape_Fruit": 73
  }
];
const colors = ['orange', 'yellow', 'lightblue']

const labels = Object.keys(data[0]).slice(1).map(l => l.replace('_', ' '));
const datasets = data.map((o, i) => ({
    label: o['ChartGroupName'],
    data: Object.values(o).slice(1),
    backgroundColor: colors[i]
  })
);

new Chart('myChart', {
  type: 'bar',
  data: {
    labels: labels,
    datasets: datasets
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          beginAtZero: true
        }
      }],
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<canvas id="myChart"></canvas>
uminder
  • 23,831
  • 5
  • 37
  • 72