Chart Thingy

by sean7777

HTML

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.min.js" integrity="sha256-ErZ09KkZnzjpqcane4SCyyHsKAXMvID9/xwbl/Aq1pc=" crossorigin="anonymous"></script>

<h1>The Data</h1>
<code class="data">[{"Chocolate":[{"kisses":[{"2022":{"jan":2000,"feb":1200,"mar":7000}},{"2021":{"jan":2000,"feb":1200,"mar":7000}}]},{"kitkat":[{"2022":{"jan":1000,"feb":3200,"mar":4500}},{"2021":{"jan":2000,"feb":200,"mar":7030}}]}]},{"Drinks":[{"Coco cola":[{"2022":{"jan":2000,"feb":1200,"mar":7000}},{"2021":{"jan":2200,"feb":1200,"mar":7100}}]},{"Pepsi":[{"2022":{"jan":1000,"feb":3200,"mar":4500}},{"2021":{"jan":4550,"feb":2100,"mar":3430}}]}]}]</code>

<h1>The Graphs</h1>

CSS

.divider {
  width: 100vw;
  height: 2vh;
  background-color: black;
}

h2 {
  text-align: center;
  text-transform: capitalize;
}

JavaScript

const $ = document.querySelector.bind(document);

/*********\
| CONFIGS |
\*********/
const graphRoot = $("body");
const months = ["January", "Febuary", "March"]
const DATA = JSON.parse($(".data").innerText);
/*************\
| END CONFIGS |
\*************/

const getKey = obj => Object.keys(obj)[0];
const getVal = obj => Object.values(obj)[0];

function createChart(chartData, chartName) {
	// Create the title, graph canvas, and divider.
  const title = document.createElement("h2");
  title.innerText = chartName
  graphRoot.appendChild(title);

  const graphElem = document.createElement("canvas");
  graphRoot.appendChild(graphElem);

  const divider = document.createElement("div");
  divider.classList.add("divider");
  graphRoot.appendChild(divider);
	
  // Create the chart
  const chart = new Chart(graphElem, {
    type: "bar",
    data: {
      labels: months,
      // Loop through the years and add the name and values.
      datasets: chartData.map(yearElem => ({
        label: getKey(yearElem),
        data: Object.values(getVal(yearElem))
      }))
    }
  });
}

// Loop through every product
// and create a chart.
for (const prodTypeElem of DATA) {
  const prodType = getVal(prodTypeElem);
  for (const prodDataElem of prodType) {
    const prodData = getVal(prodDataElem);
    const prodName = getKey(prodDataElem);
    createChart(prodData, prodName);
  }
}