Utilizing arrays in the label field of Chart.js

Creating a straightforward bar chart using Chartjs 3.x

The process involves fetching JSON data from the server, parsing it, and storing specific parts in arrays. See the code snippet below:


serverData = JSON.parse(http.responseText);
console.log(serverData);

stundenProjekt = serverData.abzurechnen.nachProjekt.map((s) => {
  return s.second.summe;
});

labelsP = serverData.abzurechnen.nachProjekt.map((p) => {
  return p.first;
});

The goal is to utilize these arrays in the data and label fields of the chart. While stundenProjekt as data functions properly, using labelsP as label does not work. Refer to the chart code below:


const data = {
  labels: labelsP,
  datasets: [{
    label: 'Projects',
    data: stundenProjekt,
    backgroundColor: ['#f4f40b'],
    borderColor: ['#B1B101'],
    borderWidth: 3,
  }]
};

if (barChartProjekt) {
  data.datasets.forEach((ds, i) => {
    barChartProjekt.data.datasets[i].data = ds.data;
    barChartProjekt.labels = newLabelsArray;  
  })
  barChartProjekt.update();
} else {
  barChartProjekt = new Chart(chart, {
    type: 'bar',
    data: data,
    options: {
      responsive: true,
      plugins: {  
        legend: {
          labels: {
            color: "white",
            font: {
              size: 18 
            }
          }
        }
      },
      scales: {
        y: {  
          ticks: {
            color: "white",
            font: {size: 18},
            stepSize: 1,
            beginAtZero: true
          }
        },
        x: { 
          ticks: {
            color: "white",  
            font: {
              size: 14
            },
            stepSize: 1,
            beginAtZero: true
          }
        }
      }
    }
  });
}

To ensure the chart displays correctly, I resorted to manually entering the contents of labelsP into the label field, essentially bypassing the original approach. The contents and workaround are detailed below:

["nexnet-SB-Cloud", "AUTEC - PSK-System²", "Fritzsche", ...]

const data = {
  labels: ["nexnet-SB-Cloud", "AUTEC - PSK-System²", "Fritzsche", ...],
  datasets: [{
    label: 'Projects',
    data: stundenProjekt,
    backgroundColor: ['#f4f40b'],
    borderColor: ['#B1B101'],
    borderWidth: 3,
  }]
};

The functionality desired is for labelsP to dynamically update with fresh data every few seconds. The mystery remains why supplying labelsP alone in the label field fails, while manually inputting its content makes the chart work flawlessly.

Answer №1

The issue lies in incorrectly adding the labels to the chart configuration.

Instead of...

barChartProjekt.labels = newLabelsArray;  

consider using this approach...

barChartProjekt.data.labels = newLabelsArray; 

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

Implementing JavaScript to showcase a list extracted from an API dataset

I'm currently undertaking a project where I am integrating an API from a specific website onto my own webpage. { "data": [{ "truckplanNo":"TCTTV___0D010013", "truckplanType":"COLLECTION", " ...

What could be the reason for the issue `injection "store" not found` showing up when attempting to call `this.store.commit()`?

I am currently working on storing values with VueX, specifically using Vuex 4.0 instead of the older version 3.0. While attempting to commit a value, I encountered an issue as follows: ... this.$store.commit("changerusername", u) ... To addres ...

"Efficient Implementation: Expo React Native Utilizes Custom Font Loading One Time Only

Hello everyone, I'm a newcomer here and I'm currently using Expo to build a react native app. My goal is to implement custom fonts in my project. I've gone through the documentation which can be found here. However, I'm facing an issue ...

Guide to implementing bidirectional data binding for a particular element within a dynamic array with an automatically determined index

Imagine having a JavaScript dynamic array retrieved from a database: customers = [{'id':1, 'name':'John'},{'id':2, 'name':'Tim}, ...] Accompanied by input fields: <input type='text' na ...

Can anyone explain to me why the data I'm passing as props to the React functional component is displaying as undefined?

I have encountered an issue with a pre-made React component where I am unable to see the data being passed as props when I console log it. I am unsure if I am passing the prop correctly, as I have used the same prop successfully in other class-based comp ...

Node.js encountered an error: TypeError - req.end does not have a function

Encountering an error stating that req.end is not a function, even though it works elsewhere in the code. Upon researching, some sources suggest that the global req variable might have been misplaced or lost. However, I haven't used any other variabl ...

Is your iPhone struggling to display animation sprites correctly?

After testing on Android and iPhone, I found that the website works great on Android but lags on iPhone. I suspected that the issue might be related to image preloading, so I tried adding a simple jQuery preloader, but it didn't solve the problem. Th ...

How to center items within a Toolbar using React's material-ui

I need help with implementing a toolbar on a page that contains three ToolbarGroup components: <Toolbar> <ToolbarGroup firstChild={true} float="left"> {prevButton} </ToolbarGro ...

How to Filter, Sort, and Display Distinct Records in an HTML Table with jQuery, JavaScript, and

In the HTML page, there will be a total of 6 tabs labeled A, B, C, D, E, and F along with 2 dropdowns. The expected behavior is as follows: The user will choose a value from the 2 dropdown menus. Based on the selected value, filtering should be applied to ...

If I type too quickly in the input field, it ends up displaying the incorrect div

I need to display two different dropdowns in my input field. To achieve this, I am using a method called shouldShowWarningBox that gets triggered every time the user updates the input and updates the value of showWarningBox accordingly. However, when I typ ...

I'm having trouble persisting my mongoose model data in my MongoDB database

Hey there, I'm new to this and currently attempting to save the Amadeus object I've created into mongosh using the .save() method. However, after connecting to my file through node, editing the Amadeus object, and running amadeus.save(), I check ...

What methods do HTML document Rich Text Editors use to incorporate rich text formatting features?

I am curious about the way text in the textarea is styled in rich-text editors. I have attempted to style text in the form but it doesn't seem to change. How does JS recognize the characters typed by the user? Can you explain this process? Edit: Aft ...

Javascript - Single line conditional statement

As I continue to improve my JavaScript skills, I'm looking for guidance on optimizing the following if statement. Is there a way to shorten it, possibly even condense it into one line? How can I achieve that? onSelect: function (sortOption) { th ...

Modifying element information in JavaScript for a Django/Heroku web application

Is it possible for me to update the values of a data object within my JavaScript code? My JavaScript receives post messages from an iframe, and I need to store this information in the correct objects. However, I am unsure if this can be done on the HTML su ...

The error message "E/Web Console(8272): Uncaught ReferenceError: functionName is not defined:1" popped up when trying to load web views within a

I'm working on incorporating webviews into a view pager. public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View v = null; v = inflater.inflate(R.layout.webview_l ...

What is the best way to retrieve router parameters within a JSX component?

How can I pass the post ID as a prop to the EditPost component in order to edit it? render() { return ( <Router> <Switch > <Route path="/edit/:id"> <EditPost index={/*what do I do here?*/} /> ...

Can the height of one div be determined by the height of another div?

Here's the specific situation I am facing: I want the height of Div2 to adjust based on the content of Div3, and the height of Div3 to adapt based on the content in Div2. The height of Div1 is fixed at 500px. Some of the questions that arise are: I ...

Understanding how events propagate in three.js

I am currently working on a scene that consists of multiple objects. To manipulate the selected object, I am using an orthographic camera controller. Specifically, I want to rotate the object with the mouse by pressing shiftKey + 1 (rotation around its own ...

Guide on how to forward the response obtained from an Ajax call to a different HTML page

I am working with a mongoose database that stores data containing an individual's first and last name. The user inputs their first name into a field, triggering an ajax request sent to the file named controller.js. This file generates a JSON response ...

There is a syntax error in the for-loop within the AngularJS $http.get causing an unexpected identifier

I'm encountering a 'syntax error: unexpected identifier' and my browser seems to be getting stuck in a loop after executing this code. I figured incorporating setInterval for delaying API requests was a sound strategy according to the API re ...