Using the data object/array in chart.js with Javascript

My challenge is to populate a data array for my chart in the following way:

data: chardata

To achieve this, I initialize a variable like so:

var chartdata = [];

The issue arises when I attempt to fill it with data from a function that should ideally return an array but ends up returning an object instead.

function getChartData(type) {
var chartdata = [];
console.log(typeof chartdata);
getDates(14).forEach(element => {
    var lastdate = new Date(element);
    lastdate.setHours(23);
    lastdate.setMinutes(59);
    lastdate.setSeconds(59);
    modlogRef.where("userName", "==", modname).where("action", "==", type).where("timestamp", ">=", element).where("timestamp", "<=", lastdate)
        .get()
        .then(function(querySnapshot) {
            chartdata.push(querySnapshot.size);
        })
        .catch(function(error) {
            console.log("Error getting documents: ", error);
        }); 
});
console.log(typeof chartdata);
return chartdata;

Upon checking the type of the variable, it shows as an object instead of an array. Thus, when I try to set this data to chardata in the chart, it fails due to being recognized as an object rather than an array.

I attempted to convert it to an array using the Object.values(chardata) method, however, this resulted in an empty array even if the object contained values.

This raises the question of what could be going wrong in my implementation?

The exact error message received is as follows:

<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="84e7ece5f6f0aaeef7c4b6aabcaab4">[email protected]</a>:7 Uncaught TypeError: Cannot read property 'skip' of undefined
    at ce (<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a6c5cec7d4d288ccd5e694889e8896">[email protected]</a>:7)
    at fe (<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="e4878c859690ca8e97a4d6cadccad4">[email protected]</a>:7)
    at me (<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="54373c3526207a3e2714667a6c7a64">[email protected]</a>:7)
    at ni.getElementsAtEventForMode (<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8be8e3eaf9ffa5e1f8cbb9a5b3a5bb">[email protected]</a>:7)
    at ni.handleEvent (<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fd9e959c8f89d3978ebdcfd3c5d3cd">[email protected]</a>:7)
    at ni.eventHandler (<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="395a51584b4d17534a790b17011709">[email protected]</a>:7)
    at i (<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="73101b1201075d190033415d4b5d43">[email protected]</a>:7)
    at HTMLCanvasElement.Fe.<computed> (<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="57343f362523793d241765796f7967">[email protected]</a>:7)

Answer №1

When working with Javascript, it's important to remember that an array is actually an object. To check if a variable is an array, you can use Array.isArray(varName).

If you're receiving an empty array as a result of your data query, it could be due to the dataset returning nothing. I debugged this by manually adding values to the array in a for loop, which successfully returned the data. It's possible that your dataset is empty or your filters are causing the issue.

https://i.sstatic.net/4UPMa.png

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

Sending information to a Google spreadsheet using JavaScript executed in a web browser

Currently, I am developing a web application that requires the user to be able to upload data directly to their own Google spreadsheet. Initially, I attempted to utilize the Google APIs Client Library for JavaScript but found that it does not include supp ...

Highcharts displaying black color after AJAX refresh

Struggling to implement real-time data visualization using Highcharts, I found myself tired of sifting through documentation and feeling confused. My solution involves using AJAX refresh. When the page initially reloads, my chart renders properly. However, ...

Passing Data to a Different Route in Vue.js

Being new to Vue.js, I have a question on how to efficiently handle data retrieval from my backend application. Here is the code snippet that fetches all the data: var app2 = new Vue({ delimiters: ['%%', '%%'], el: '#app2& ...

Bootstrap DataTable lacks responsiveness

Having trouble with my Bootstrap DataTable. I followed the documentation and added the necessary HTML and Javascript code, but the table is not responsive or flexing as expected. I have checked all the links and imports, so I'm unsure where the issue ...

Why does passing a number from HTML to a JS function result in it becoming "undefined" in JS?

Below you will find a snippet of PHP and HTML: <?php $rowCountInDataTable=600; ?> ... <button onclick="<?php echo "showNextRows($rowCountInDataTable)"; ?>"></button>; Also included is some JS code: function showNextRows(totalRowC ...

Which callback function is best suited for handling the response in an XMLHttpRequest and rendering it on the webpage?

Upon a user action on the page, an AJAX request is made to my Node.js Express server to send data. Here's what happens next: router.post('/', function(req, res){ //user authentication first, then inside that callback res.redirect('/d ...

Understanding the Importance of Nullable Arrays in Programming

When I come across code snippets like this, I interpret it as making an array nullable. However, I am puzzled as to why we would need to do this, considering that arrays are already reference types, thus inherently nullable. Therefore, my question is: wha ...

Constructor of parent class that accepts an instance of the parent class as an argument

Here is a sample code snippet: public class Parent { int num; Parent p; Parent() { } Parent(Parent s) { p=s; } void Print() { System.out.println(p.num); } } and: public class Child { ...

Error Message in Three.js: "Function is not defined in Perspective Camera"

My program was functioning well, but now I'm encountering the "undefined is not a function" error within the three.js file. The problematic line is 10466 in the uncompressed library, specifically within the declaration of THREE.PerspectiveCamera. Wher ...

The modal will appear only if it is not initially hidden

Recently, I was tasked with incorporating a modal into a WooCommerce product page that appears when the 'add to cart' button is clicked. To initiate this process, I decided to adapt and use an example modal from w3schools. After tweaking the code ...

Tips for resolving the error "Module not found: Unable to locate '@babel/runtime/core-js/map' in Material-UI"

While working with React using Material UI, I recently updated Material-UI to the latest version and encountered the following error: ../node_modules/material-ui/styles/withStyles.js Module not found: Can't resolve '@babel/runtime/core-js/map&a ...

Automatically move to the latest message as soon as it is posted

After trying multiple codes and encountering issues, I am attempting to add my message in a textarea that will automatically scroll down. Even though I have my own codes, they don't seem to work properly. I also tried using the code provided Here. ED ...

When utilizing date-fns and comparing dates with isWithinInterval in a specified timezone, an error occurs indicating an invalid interval

For my upcoming project, I am retrieving UTC time from an API. To ensure accuracy, I need to convert the UTC times to the local time of the user based on their timezone setting obtained from the API. I attempted to utilize the isWithinInterval function fr ...

Prevent swiping beyond the final slide in a react-slick carousel

I am currently using react-slick to create a carousel, and I have a specific requirement to prevent swiping and dragging of slides once the last image is reached. After conducting some research, I attempted to set swipe: false on the final slide, which suc ...

Whenever I attempt to run my script, the console on replit fails to function properly

As a complete beginner to Javascript, I'm having trouble getting my script to respond when I try to execute it. It just moves on to the next line and waits for me to type 'node index.js' again. I've included 2 images in an Imgur album - ...

Extract data from the Ajax database and automatically hide the "Load More" button when all items

Every time I fetch data from my MySQL database, I retrieve 5 items at once. $query = $pdo->prepare("SELECT * FROM names WHERE id < ? ORDER BY id DESC LIMIT 5"); $query->execute([$_POST["id"]]); while($row = $query -> fetch() ...

jQuery AJAX requests operate in a linear sequence and do not execute concurrently

I need assistance with setting up a progress bar to show the progress of a lengthy task of importing a large CSV file into a database. The process starts with an initial jQuery.ajax call and a timeout is set to retrieve the progress in percentage from the ...

AngularJS routing is malfunctioning, only appending a hash symbol

After diving into AngularJS, I was excited about the possibilities it offers once mastered. However, at my current stage, I am feeling quite frustrated. My main issue lies with implementing routing. Despite a seemingly error-free console, Angular refuses t ...

The ReactJS Header Design, Avoid using <Link> without being wrapped inside a <Router>jsx component

I'm currently working on a Layout component that will display both the Header and Footer. However, I encountered an issue while trying to create a menu list in the Header.jsx file. Error: You should not use <Link> outside a <Router> I am ...

Encountering silence: React JS fetch call left unanswered by Sinatra server

Exploring the realms of Sinatra and React JS, I am venturing into making a GET call from my React website to a Sinatra server in order to display plain text. The Sinatra Server script: require 'sinatra' set :root, 'lib/app' before d ...