Setting line chart data for Chart.js

Can you help me troubleshoot an issue I'm facing with creating a dataset for a line chart in Chart.js? Despite having an array of objects, the dataset isn't rendering correctly and I end up with two line charts instead of one. What could be causing this confusion?

const data = [{May 04: '', May 05: '1', May 06: ''}, {May 04: '2', May 05: '', May 06: ''}]

const chartData = {
           labels: ['May 04', 'May 05', 'May 06' ],
          datasets: prepareDataSet(data),
        };

const prepareDataSet = (data) => {
  const dataSet = [];


  dataSet.push({ label: 'Total' });
  data.forEach((v) => {
  dataSet.push({
    data: Object.values(v),
  });
})
  return dataSet;
};

Answer №1

If you're looking for a solution to your issue, consider implementing the code below:

const data = [
  { 'May 04': '', 'May 05': '1', 'May 06': ''},
  { 'May 04': '2', 'May 05': '', 'May 06': ''}
];

const getDataSet = data => {  
  const dsData = [0, 0, 0];
  data.forEach(obj => Object.values(obj).forEach((value, index) => dsData[index] += Number(value)));
  return { 
    label: 'Total', 
    data: dsData
  };
};

const chartData = {
  labels: ['May 04', 'May 05', 'May 06'],
  datasets: [getDataSet(data)]
};

console.log(chartData);

If your data is subject to change, customization can be achieved through the following approach:

const data = [
  { 'May 04': '', 'May 05': '1', 'May 06': '', 'May 07': '1' },
  { 'May 04': '2', 'May 05': '', 'May 06': '', 'May 07': '2' }
];

const getDataSet = data => {  
  const dsData = Object.keys(data[0]).fill(0);
  data.forEach(obj => Object.values(obj).forEach((value, index) => dsData[index] += Number(value)));
  return { 
    label: 'Total', 
    data: dsData
  };
};

const chartData = {
  labels: Object.keys(data[0]),
  datasets: [getDataSet(data)]
};

console.log(chartData);

const data = [
  { 'May 04': '', 'May 05': '1', 'May 06': '', 'May 07': '1' },
  { 'May 04': '2', 'May 05': '', 'May 06': '', 'May 07': '2' }
];

const getDataSet = data => {  
  const dsData = Object.keys(data[0]).fill(0);
  data.forEach(obj => Object.values(obj).forEach((value, index) => dsData[index] += Number(value)));
  return { 
    label: 'Total', 
    data: dsData
  };
};

const chartData = {
  labels: Object.keys(data[0]),
  datasets: [getDataSet(data)]
};

new Chart('myChart', {
  type: 'line',
  data: chartData,
  options: {
    scales: {
      y: {
        ticks: {
          stepSize: 1
        }
      }
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.8.0/chart.min.js"></script>
<canvas id="myChart" height="80"></canvas>

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

What is the best way to synchronize the state of a component with the updated value in a Vuex store?

Within my Vuex store, I have implemented mutations that receive a message from one component and are responsible for showing/hiding a prompt message in another component (similar to displaying a "You are logged in" prompt after a successful login): setPro ...

Avoid sudden page movements when validating user input

After successfully implementing the "Stars rating" feature from https://codepen.io/462960/pen/WZXEWd, I noticed that the page abruptly jumps up after each click. Determined to find a solution, I attempted the following: const labels = document.querySelect ...

What is the best way to run a lengthy task in Node.js by periodically checking the database for updates?

In my current setup, there is a routine that continuously checks the database for any pending work orders. Upon finding one, it needs to execute it promptly. The system can handle only one work order at a time, and these tasks may vary in duration from 5 s ...

Browserify does not provide access to the require function in the browser environment

I am currently in the process of developing a web application using node.js along with express. My goal is to leverage Browserify in order to expose my local modules to the browser. Here is the structure of my application: ├── app.js ├── lib ...

trigger an event once an element has completed cycling using cycle.js

Incorporating the cycle.js library for simple transitions between images: $(document).ready(function() { var first; var $slider = $(".trauringe"); $slider.cycle({ timeout: 8000, next: '#next', prev: '#prev' ...

What is the best method for sending a document to a web API using Ajax, without relying on HTML user controls or forms?

I have successfully utilized the FormData api to upload documents asynchronously to a web api whenever there is a UI present for file uploading. However, I now face a situation where I need to upload a document based on a file path without relying on user ...

The use of Array.push() within an $http.get() function in AngularJs results in an array with unexpected

I'm stuck trying to debug my code, particularly because it seems to be related to a javascript issue. The problem arises when I attempt to load a local txt file using $http.get (is there another method that might work better?). The goal is to store t ...

triggering a function from a child component in React

I am facing a challenge in calling a function from the parent component that is stored in a child component. I understand how to do it from child to parent using props, but unsure about how to achieve it from parent to child. In the example below, you can ...

What is the reason behind only the initial click boosting the vote count while subsequent clicks do not have the same

In this snippet of code: //JS part echo "<script> function increasevotes(e,location,user,date,vote) { e.preventDefault(); var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (this.readyState ...

Does the rendered ID of an ASPX control always appear the same in the source HTML code?

Let's say I have an aspx textbox with id="txtkms". In the HTML view source, it appears as ContentPlaceHolder1_Gridview1_txtkms_1. I'm curious if this control will always be rendered as ContentPlaceHolder1_Gridview1_txtkms_1 every time I run my as ...

Create an array in JSON format that includes a JavaScript variable, with the variable's value changing each time a mouse

var question="What is your favorite color?"; var option="red"; var col=[]; When the user clicks, the variable value changes and values should be pushed in a specific format. I am new to JavaScript, please help me with this. Thank you. //On click, the var ...

Using jQuery to handle nested div elements and triggering a click event only once when the inner div is clicked

I have a situation where I have nested divs. When the inner div (closeme) is clicked, I do not want the click event of the outer div (container) to be triggered. How can I achieve this? html <div id="container"> content <div id="closeme">< ...

Is it possible for Error 419 (status unknown) to be caused by a factor other than the CSRF-Token?

I'm currently facing a difficulty in resolving an issue in my application that is connected to the error mentioned above. While searching for a solution, all I come across is guidance on managing CSRF tokens and nothing else. Could it be that the err ...

Looking to automate clicking in Vue.js?

Upon pressing the search button, I need to display the products in the background and choose one. Here are the codes: //Specify the area to click each time <div v-for="(item, index) in filteredProducts" @click="addToList(item)">& ...

Pass along the value of a link upon clicking on it

I have implemented a simple list using md-data-table: <tr md-row md-select="device" md-on-select="logItem" md-auto-select="options.autoSelect" ng-repeat="device in devices.data"> <td md-cell style='text-align:left;vertical-align:middle&apo ...

Center rotation with THREE.TrackballControls

I'm facing an issue with rotating an object on the scene using THREE.TrackballControls. The rotation is not relative to the object's axis when it's not in the center of the screen - instead, it rotates based on the center of the screen. I at ...

Trigger a function when <a> is clicked, which will then increment the count by one and reflect this change in the database

The database generates the content of this div ordered by a count number called "cts". Whenever I click on the div, I want the "cts" number to increase by one, and then update the change in the database. This will result in the content changing accordingly ...

Removing error messages upon form reset initiated by an API request

Is there a way to clear error messages that appear beneath a text field when resetting form fields with values from an api call? In my Formik form, I have three fields that are loaded from an api database call along with a Reset button that reloads these ...

Transforming dates in JavaScript

So I have a situation where I need to call php from javascript. The URL address is Jun 18 18:00:00 UTC+0200 in the year 2013, but that format is not suitable for my needs. I want to convert it to the format YYYY-MM-DD, either using JavaScript or PHP. An ...

Ajax ensures that the site stays active and responsive

Struggling to understand how to make this code work. var request; if(window.XMLHttpRequest){ request= new XMLHttpRequest(); }else{ request = new ActiveXObject("Microsoft.XMLHTTP"); } var handleStateChange = function () { switch (request.re ...