Using JavaScript Arrays to Make Labels in Chart.js

I am currently working with Chart.js and have a JavaScript array containing values that look like this:

var obj = JSON.parse('{"0":"8.4113","2":"9.5231","3":"9.0655","4":"7.8400"}');

I am passing the "obj" array to my Chart.js, filling out the bars successfully:

var barChartData = {
        labels : obj1,

        datasets : [
            {
                fillColor: "rgba(151,187,205,0.5)",
            strokeColor: "rgba(151,187,205,0.8)",
            highlightFill: "rgba(151,187,205,0.75)",
            highlightStroke: "rgba(151,187,205,1)",
                data : obj

            }
        ]

    }
    window.onload = function(){
        var ctx = document.getElementById("canvas").getContext("2d");
        window.myBar = new Chart(ctx).Bar(barChartData, {
            responsive : true
        });
    }

    </script>

However, there is a second array named "obj1" which contains label names for the chart as follows:

 var obj1 = JSON.parse('{"0":"name1","2":"name2","3":"name3","4":"name4"}');

Despite having the label names in the "obj1" array, the labels are still empty on the chart. I am uncertain why this array is not working as expected compared to the data array.

Answer №1

Here is a solution that appears to be effective:

function transformObjectToArray(data) {
    return Object.keys(data).map(function(key) {
        return data[key];
    });
}

var data = JSON.parse('{"0":"8.4113","2":"9.5231","3":"9.0655","4":"7.8400"}');
var labels = JSON.parse('{"0":"name1","2":"name2","3":"name3","4":"name4"}');

data = transformObjectToArray(data);
labels = transformObjectToArray(labels);

var chartData = {
    labels : labels,
    datasets : [
        {
            fillColor: "rgba(151,187,205,0.5)",
            strokeColor: "rgba(151,187,205,0.8)",
            highlightFill: "rgba(151,187,205,0.75)",
            highlightStroke: "rgba(151,187,205,1)",
            data : data

        }
    ]
};
var ctx = document.getElementById("canvas").getContext("2d");
window.myBarChart = new Chart(ctx).Bar(chartData, {
    responsive : true
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.2/Chart.js"></script>
<canvas id="canvas"></canvas>

Object.keys(data) retrieves an array of the object's keys, which are then transformed into values using the Array#map() function. This results in a new array containing only the values.

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

Accessing a JSON file in JavaScript

My website has a script that populates dropdown menus and is currently running from a custom.js file. While it works well, there is one aspect of it that I am not entirely satisfied with. The script involves embedding the various levels of menu, which am ...

Is there a way to deactivate keyboard input on an HTML number input field? How about in a React or Material-UI environment?

I am working with an <input> tag that has the attribute type="number", and I want to disable keyboard input so that users are required to adjust the value using the spinner (up and down arrows). This will allow me to consume the input value on each c ...

Analyze a designated section and display the top 3 frequently used words

Below is the code snippet provided: <body> <div id="headbox"> <p>Whatever...</p> </div> <div id="feed"> <div> <p>I hate cats</p> </div> <div> <p>I like ...

What is the reason for the inability to access a global variable type variable outside of the $.each function when used within the $

While analyzing a code snippet, I came across an issue with a variable causing an error. function call(data) { $.each(data, function(index, value) { var ddlId = 'ddlCat' + data[index].docId; var html = '<tr id="supp_doc_row_&ap ...

A guide to performing a LEFT JOIN on two JSON data sources from external URLs

I've been attempting to achieve the following outcome using external JSON data but haven't had any luck finding a solution on search engines or forums. Can anyone provide assistance with this? Thank you in advance. people = [{id: 1, name: "Tom" ...

Can an older style class be inherited from an ECMAScript 6 class in JavaScript?

When I run the code below on Node.js version 4.2.1: 'use strict'; var util = require('util'); class MyClass { constructor(name) { this.name = name; } } function MyDerived() { MyClass.call(this, 'MyDerived'); } ...

Encountered an issue: too many elements in character array initializer while attempting to display an array of strings

I attempted to print out an array of strings but encountered an error: excess elements in char array initializer. Can someone provide a hint on what is wrong with this code? Step 1 involved changing '' to "", but nothing changed, the s ...

Improving JavaScript Functions: Minimize duplication of helper methods

I have a set of helper functions that check for the presence of specific strings in an array and certain steps before triggering other functions. The reason for keeping them separated is because arrTours must be associated with only those arrSteps. // Help ...

Material-UI icons refusing to show up on the display

I've been working on creating a sidebar component and importing various icons to enhance the UI, but for some reason they are not displaying on the screen. I even tried other suggested solutions without success. <SidebarOption Icon = {InsertComment ...

Unlock the Full Potential: Enabling Javascript's Superpowers through PHP Execution

I specialize in PHP and JavaScript. Currently, I am attempting to incorporate JavaScript functionalities into my PHP code. However, I am encountering an issue where the code is not functioning properly. The PHP code that executes the JavaScript code is as ...

Can you explain the term 'outer' in the context of this prosemirror code?

Take a look at this line of code from prosemirror js: https://github.com/ProseMirror/prosemirror-state/blob/master/src/state.js#L122 applyTransaction(rootTr) { //... outer: for (;;) { What does the 'outer' label before the infinite loop ...

What is the best way to determine whether a YouTube video permits embedded playback?

When working with user-generated content, it's important to note that YouTube channels may restrict their videos from being played in an embedded player. In order to provide a better user experience, I need to detect the specific reason why a video ca ...

Exploring the process of passing an array as a function argument from PHP to JavaScript

I am looking for assistance in passing an array as a function argument from PHP to JS. The values I need are retrieved from a database. while ($rows = pg_fetch_array($qry)) { ?> <option value="<?php echo $rows[&ap ...

The issue of variable stagnation in Firefox content script while utilizing self.port.on

I'm having trouble updating the version var as intended. When I try to update it with the following code: self.port.on("get-version", ver => { version = ver; alert(version); }); An alert pops up displaying the correct version number, but the HTML ...

Prevent a form from loading depending on the response received from an ajax callback

I am currently working on implementing an ajax post function. The process involves sending data and receiving a callback from PHP with some data in return. Depending on the returned data, I need to make a decision whether to proceed or allow the user to re ...

Guide on integrating a custom language parser and syntax validation into Monaco editor

I am in need of guidance on how to define a custom language in the Monaco editor. Despite my efforts, I have been unable to locate a reliable source for this documentation. My goal is to create a language with syntax similar to JavaScript, enabling users ...

Ways to verify if the current date exists within a TypeScript date array

I am trying to find a way in typescript to check if the current date is included in a given array of dates. However, even after using the code below, it still returns false even when the current date should be present within the array. Can anyone please pr ...

"Transmit the document by utilizing the file ID in the form of

When sending a file from my server, I can easily define the path and it goes through successfully. However, with the node-telegram-bot-api, there is an option to send a document that is already hosted on telegram servers by providing the file_id in the doc ...

The art of sketching precise lines encircling a circular shape through the

What is the best way to use a for loop in JavaScript to draw lines around a circle, similar to those on a clock face? ...

What is the method to show text on hover in angularjs?

I'm a beginner in AngularJS and I'm looking to show {{Project.inrtcvalue}} when the mouse hovers over values. Can anyone guide me on how to achieve this using AngularJS? <table ng-table="tableParams" show-filter="true" class="table" > ...