Parse a JSON object to ChartJS

0👍

Ok… i’ve tried this and it seems to work.
So the basic idea is you get the array of keys and values and provide them to labels as well as data.
Here’s a basic example based on the data you provided.

index.html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <canvas id="myChart" width="400" height="400"></canvas>

  <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
  <script src="./script.js"></script>
</body>

</html>

and the script file

Script.js
const toCharts = () => {
  const exampleData = {
    "2021-6-12": 2,
    "2021-6-13": 3,
    "2021-6-14": 1
  }

  const ctx = document.getElementById('myChart').getContext('2d');
  const myChart = new Chart(ctx, {
    type: "bar",
    data: {
      labels: Object.keys(exampleData),
      datasets: [{
        label: "Demo years",
        data: Object.values(exampleData),
        backgroundColor: [
          'rgba(255, 99, 132, 0.2)',
          'rgba(54, 162, 235, 0.2)',
          'rgba(255, 206, 86, 0.2)',
        ],
        borderColor: [
          'rgba(255, 99, 132, 1)',
          'rgba(54, 162, 235, 1)',
          'rgba(255, 206, 86, 1)',
        ],
        borderWidth: 0.5,
      }]
    },
    options: {
      scales: {
        y: {
          beginAtZero: true
        }
      }
    }
  })
}

toCharts();

👍:1

You can use Object.keys() and Object.values() to map your object into labels and datasets, as follows :

const chartData = {
  "2021-6-12": 2,
  "2021-6-13": 3,
  "2021-6-14" : 1,
}
const labels = Object.keys(chartData) // labels
const data = {
  labels: labels,
  datasets: [{
    label: 'My First Dataset',
    data: Object.values(chartData),   // datasets
...

Object.keys(chartData) will map your object ‘key’ : 2021-6-12, …

And, Object.values(chartData) will map your object data : 2,3,…

See reference here :

Object.keys()

Object.values()

Leave a comment