No chart display for Chart.js and JSON data

๐Ÿ‘:0

I added comments in the code to explain what I am doing. Let me know if you have any questions.

I believe your issue was with the background colors. You provided a string where you need an array with a value for each data value. See what I did with the two random functions to generate the colors.

/**
 * Generate a random number between 0-255
 */
const getRandomNumber = () => {
  return Math.floor(Math.random() * 256);
}
/**
 * Generate a random number rgb values
 */
const getRandomRgba = () => {
  return `rgba(${getRandomNumber()},${getRandomNumber()},${getRandomNumber()}, 0.3)`;
}
// data provided
const data = [{
    "dept_name": "BAKASS",
    "total": "14"
  },
  {
    "dept_name": "BKKM",
    "total": "7"
  },
  {
    "dept_name": "CDC",
    "total": "5"
  },
  {
    "dept_name": "DENGGI",
    "total": "10"
  },
  {
    "dept_name": "ENTOMOLOGI",
    "total": "4"
  }
]
// arrays for chart
var labels = [];
var dataArr = [];
var colors = [];

// populate the array. 
// you used a for-in loop which gives you the index, not the object. 
// this way you do not need to do data[x] as it returns the object itself. 
for (const obj of data) {
  const {
    dept_name,
    total
  } = obj; // destruture the object
  labels.push(dept_name);
  // optional to convert to float. Did this to save chartjs a step.   
  dataArr.push(typeof total === "string" ? parseFloat(total) : total);
  // you can do this if you like
  // dataArr.push(total);
  colors.push(getRandomRgba());
}

// build chart obj
var chartdata = {
  labels,
  datasets: [{
    label: "Total",
    data: dataArr,
    backgroundColor: colors,
    hoverOffset: 4
  }]
};
const idPrefix = "department-"
const chartTypes = ["pie", "doughnut", "bar", "line"];

// lets make a chart for each type. 
let charts = {};
for (const type of chartTypes) {
  const id = idPrefix + type;
  var ctx = document.getElementById(id);
  const config = {
    type: type,
    data: chartdata,
  };
  var chart = new Chart(ctx, config);
  const obj = {
    ctx,
    chart
  }
  charts[type] = obj;
}
.card {
  max-width: 550px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>



<div class="card">
  <div class="card-header">Department Pie</div>
  <canvas id="department-pie" class="__chart"></canvas>
</div>
<hr>
<div class="card">
  <div class="card-header">Department Doughnut</div>
  <canvas id="department-doughnut" class="__chart"></canvas>
</div>
<hr>
<div class="card">
  <div class="card-header">Department Line</div>
  <canvas id="department-line" class="__chart"></canvas>
</div>
<hr>
<div class="card">
  <div class="card-header">Department Bar</div>
  <canvas id="department-bar" class="__chart"></canvas>
</div>

Leave a comment