score:0

Accepted answer

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();

score: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()


Related Query

More Query from same tag