Utilize a JSON object with ChartJS for data visualization

Recently, I've been working with a REST API that returns historical data in the following format:

{
  "2021-6-12": 2,
  "2021-6-13": 3,
  "2021-6-14" :1
}

This data represents the count of measurements taken on each date. I'm wondering if there is a way to visualize this data using ChartJS, with the dates as labels and the counts as datasets displayed in a bar chart?

Answer №1

If you want to convert your object into labels and datasets, you can leverage Object.keys() and Object.values(). Here's how:

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

The function Object.keys(chartData) will map the keys of your object such as '2021-6-12', ...

Similarly, calling Object.values(chartData) will map the values in your object like 2, 3, ...

For more information, check out these references:

Object.keys()

Object.values()

Answer №2

Alright, after experimenting with this approach, it seems to be effective. The concept is straightforward - you gather the array of keys and values and supply them to labels and data. Below is a simple example based on the provided data.

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>

including the script file

Script.js
const toCharts = () => {
  const sampleData = {
    "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(sampleData),
      datasets: [{
        label: "Demo years",
        data: Object.values(sampleData),
        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();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

adding numerous items to an array using JavaScript

How can I add multiple objects to an array all at once? router.post(`/products`, upload.array("photos" , 10), async (req, res) => { console.log(res); try { let product = new Product(); req.files.forEach(file => { product.p ...

The challenge with encoding URL in Ajax requests

I am trying to send an encrypted message along with the corresponding key (two-way encryption) to a PHP page for decryption, and then receive the decrypted result in the response. Below is an example of how I am attempting to send the encrypted message us ...

Attempting to retrieve dynamically generated input fields and cross-reference them with structured length .json data

In the process of developing code, I've implemented a for loop to dynamically generate HTML input fields based on the length of some data in a .json file. My goal is to use jQuery to compare the text entered in each input field with the corresponding ...

Integrating Excel into a webpage - is it possible?

Currently facing an issue on my website. I'm trying to open a 'file://' URL directly with the <a href=""> element in a browser, but it's prohibited. I'm searching for a plugin or similar solution that can enable me to execut ...

Three.js fails to load due to Require.js issue

Having encountered a JavaScript error in browser (on the last line mentioned above) with generated code from TypeScript: define(["require", "exports", "three", "jquery", "./test"], function (require, exports, THREE, jQuery, Test) { var Main = (function () ...

Understanding the Variable Scope in Event Listeners and Asynchronous AJAX Functions

Here's a question that might seem simple to some, but I'm not sure. So, when you register an event listener within an asynchronous function, one would think that all values within that function would be inaccessible once the function has complete ...

a service that utilizes $http to communicate with controllers

My situation involves multiple controllers that rely on my custom service which uses $http. To tackle this issue, I implemented the following solution: .service('getDB', function($http){ return { fn: function(){ return $http({ ...

Plow through the contents of the S3 Bucket, exploring every Folder and File

I've encountered an issue while iterating through an S3 bucket using s3.listObjects. The error message { [UnexpectedParameter: Unexpected key 'Key' found in params] has been popping up. Below is the snippet of code I'm currently working ...

Is conditional CSS possible with NextJS?

While working on an animated dropdown for a navbar, I came across this interesting dilemma. In a strict React setup, you can use an inline if/else statement with onClick toggle to manage CSS animation styles. To ensure default styling (no animation) when ...

What could be causing my list of files to not properly append to FormData?

I have been working on this issue for the past three days. Despite trying various solutions from different sources, including seeking help from other websites, I am still unable to resolve it. My current challenge involves sending a post request with a Fo ...

Encountering the "Cannot Retrieve" error in express.js while navigating to the ID of an object

I'm in the process of developing a blog web app that allows users to create articles. Once a user clicks on 'new article', they will be taken to a page with a 'post article' button. This button triggers a post request linked to my ...

Strategies for Repurposing local file.js across multiple Vue projects

I have a file called myfile.js with functions that I want to reuse in multiple vue projects, specifically within the App.vue file. Here is the file structure: -- projec1 ---- src ------ App.vue -- project2 ---- src ------ App.vue -- myfile.js Directly ...

Display text on the screen with a customized design using JavaScript's CSS styles

I need help with printing a specific page that contains some information designed in print.css. I want to print this page, including an image, with the same style. function printContent() { var divContents = document.getElementById("terms").innerH ...

Any suggestions on how to retrieve data into Tabulator using the POST method?

I am currently utilizing Tabulator 4.6 and have an API that supports the POST method. My goal is to retrieve data from Tabulator through a POST request instead of a GET request. Within my org.js file, I have the following configuration: var ajaxConfig = { ...

What is the process of substituting types in typescript?

Imagine I have the following: type Person = { name: string hobbies: Array<string> } and then this: const people: Array<Person> = [{name: "rich", age: 28}] How can I add an age AND replace hobbies with a different type (Array< ...

Executing database queries in a synchronous manner in JavaScript

let positionConfig = require('setting'); function retrieveConfig(element) { let setting; positionConfig.find({element: element}, function (err,docs) { console.log(docs[0].current); // show the value setting = docs[0].curr ...

Creating a unique texture on a spherical object using THREE.js

Can a sphere be textured in sections rather than all at once? Just like we can use 6 textures on 6 sides of a cube, is it possible to apply different textures to different parts of a sphere? For example, dividing the sphere into quarters and texturing each ...

Discovering the functionality of detecting the pressing of the "enter" key within an input field that triggers the next button in Internet Explorer versions 8 through 10

My current challenge involves detecting Internet Explorer's behavior when the Enter key is pressed in an input box with a button element beside it, especially when they are not enclosed within a form element. This unique feature of IE is intriguing b ...

Vue not displaying information from API calls

After developing my own backend API, I encountered a strange issue. When I test the API on Chrome, it functions perfectly fine. However, when I attempt to consume the API using Axios in Vue, no data is returned. axios.get('http://192.168.149.12:8888/ ...

Dynamic jquery panel that remains expanded while concealing the menu on large screens

The page demonstrating jquery features automatically opens a side panel on large screens and displays a logo image instead of the standard 'open panel' icon. It remains open until the screen size is reduced. Take a look at the demonstration here: ...