Tips for swapping out the data array in my ChartJS graph

I am currently working on a project that involves changing the data array of a chart with a completely different one. Unfortunately, although my code is successfully updating the labels of the chart, the data itself remains unchanged and I cannot figure out why. Your assistance in resolving this issue would be greatly appreciated. Thank you in advance.

Below is the code snippet:

var label = [];
var testArray= [{"production":"12","mois":"janvier"},{"production":"5","mois":"février"},{"production":"9","mois":"mars"},{"production":"17","mois":"avril"},{"production":"6","mois":"mai"},{"production":"8","mois":"juin"},{"production":"17","mois":"juillet"},{"production":"7","mois":"aout"},{"production":"10","mois":"septembre"}];
var chartData = {
    labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
    datasets: [{
        label: '# of Votes',
        data: [7, 4, 3, 5, 2, 3]
    }]
};
var newdata = [];

function updateData(){
    chartData.datasets.data = testArray.map(function (item) {
        return item.production;
    });

    chartData.labels = 
testArray.map(function (item) {
        return item.mois;
    });
    graphique.destroy();
    graphInit();

}


function graphInit() {
    graphique = new Chart(ctx, {
        type: 'bar',
        data: chartData,
        options: {
            scales: {
                yAxes: [{
                    ticks: {
                        beginAtZero: true
                    }
                }]
            }
        }
    });
} 

Answer №1

When working inside the function updateData, make sure to access the data using chartData.datasets[0].data. It is important to update the data with an array of numbers instead of strings. You can achieve this by utilizing the Number method to convert strings to numbers like so:

chartData.datasets[0].data = testArray.map(function (item) {
    return Number(item.production);
});

A simpler way to write the above code snippet would be:

chartData.datasets[0].data = testArray.map(item => Number(item.production));

Instead of calling both graphique.destroy() and graphInit(), you can streamline your code by replacing them with graphique.update(). For additional assistance, you may find this answer helpful: .

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

Troubleshooting Error in WebSocket with 'ws' Library in Node.js and Vue.js: Issue with RSV1 Flag Unset

I've come across a problem with WebSocket connections while working on my Node.js and Vue.js project. I've implemented the 'ws' library for WebSocket functionality, but I keep getting the error message "Invalid WebSocket frame: RSV1 mus ...

Refresh the Google chart in response to a state change in Vuex

Currently, I am working on a reporting page that will display various graphs. Upon entering the page, an API request is made to retrieve all default information. The plan is to enable users to later select filters based on their inputs. For instance: init ...

What could be causing the error 'i is not defined' in my Vue.js component script when using a basic for loop?

I have a task where I need to sort an array by version and then move all elements starting with 'ipad' to the end of the list. This code snippet is extracted from a single file Vue.js component: computed: { orderedUsers: function () { ...

Creating a basic bar graph using d3.js with an array of input data

In my dataset, I have an array of form data that includes items like 'Male', 'Female', 'Prefer Not To Say'. I want to create a simple bar chart generator using D3.js that can display the percentages or counts of each item in t ...

"What is the best way to manipulate arrays in vue.js using the map function

I'm currently dealing with a Vue code that incorporates anime.js. My code has grown substantially to over 1500 lines. In order for Stack Overflow to accept my question, I have only included 5 items of my sampleText, even though it actually consists of ...

Strip excess white space from a complex string using Javascript

I have the following sets of strings: 14/04/22 10:45:20 12.08N 87.65W 15.0 2.9ML Frente a Corinto 14/04/21 11:05:34 12.10N 87.70W 140.0 3.5MC Cerca de Masachapa 14/04/22 09:00:09 12.35N 86.44W 12.4 1.3ML Cerca del volcan Momotombo 14/04/21 23:33:37 1 ...

Analyzing a Specific DropDown Based on Condition

In my MVC project, I am working on a form that should be accessible based on certain conditions. The first view includes a dropdown list and a submit button. I want the value selected in the dropdown list to be passed and compared against a set condition. ...

Mastering Data Transmission: Sending and Receiving Various Data Types Between React and Flask

Looking to send both user image and user data together to create a user on the backend using Flask. Currently, I am sending it as parameters but would like to include everything in the body of a POST request in React. React: const newData = new FormData( ...

Having difficulty grasping the concept behind the prepend method's functionality

I encountered an issue with my code, where I successfully created a <th> element initially, but faced problems when trying to create it repeatedly. function createTH(){ var noOfRow = document.getElementById("addItemTable").rows.length; var t ...

Obtaining the text content of a <div> element when clicked using Selenium

I am trying to extract the email address from the code snippet below, but I am unsure of how to do it. Any assistance would be greatly appreciated! <div class="taLnk hvrIE6 fl" onclick="ta.trackEventOnPage('Listing', 'Email', 774169 ...

Combining multiple JSON objects in an array into one single object with the help of jQuery

My array consists of JSON objects like the ones shown below: [{ "Name": "Nikhil", "Surname": "Agrawal" }, { "profession": "java developer", "experience": "2 years" }, { "company": "xyz", "city": "hyderabad" }] What I aim to achiev ...

A guide on updating a JSON object based on specific criteria

I'm dealing with two JSON files here - the first one is named origin.json, and the second one is called newData.json. My goal is to update the child value of Origin based on the data in NewData. However, I only want this update to impact items that a ...

Error: Undefined object while trying to access 'injection' property

After updating to React 16.x, I encountered the following error: Uncaught TypeError: Cannot read property 'injection' of undefined at injectTapEventPlugin (injectTapEventPlugin.js:23) at eval (index.js:53) at Object.<anonymous> ...

Having difficulty accessing the selected input value from window.localstorage

<script> (function(window, document, undefined) { function saveFormData(event) { if(event.target.type=='checkbox' || event.target.type=='radio') { window.localStorage.setItem(event.target.id, event.target. ...

Is it advisable to implement the modular pattern when creating a Node.js module?

These days, it's quite common to utilize the modular pattern when coding in JavaScript for web development. However, I've noticed that nodejs modules distributed on npm often do not follow this approach. Is there a specific reason why nodejs diff ...

MUI Error: Unable to locate module - "Error: Unable to resolve 'moment' module"

Encountering numerous errors when attempting to utilize the date-picker feature from mui-x. Issue: Module not found - Error: Can't resolve 'moment' Problem locating '@mui/x-date-pickers/LocalizationProvider' Error: Module not fou ...

Issue with Node.js OAuth authentication

As someone new to Node.js and specifically OAuth, I have been exploring the use of Google APIs with Node.js. So far, here is what I've accomplished: var fs = require('fs'); var readline = require('readline'); var google = require( ...

Angular restricts the use of the svg namespace in the $sce service for security reasons

I have a project in Angular Material where I am using an md-icon with a specific svg structure: <md-icon class="ic1" md-svg-src='data:image/svg+xml, <svg xmlns="https://www.w3.org/2000/svg" viewBox="0 0 32 32"> <ellipse ry="16" rx=" ...

Ways to eliminate the index of the parent array from an array

Eliminating the parent array index within an array is my current objective. This is the array I am working with: Array ( [0] => Array ( [0] => Array ( [id] => 296 [u ...

Server issues causing Laravel 6 CSS and JS to fail loading

I compressed my project folder and uploaded it to the Document Root for the subdomain. All of my CSS and JS files are located inside the Public folder. The project works perfectly fine on XAMPP, but when I transfer it to my shared hosting, the CSS and JS f ...