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

Tips for Keeping Sub Menu Visible Without Having to Click

I am working on an HTML navigation menu that opens submenus on click like this... $("#nav_evnavmenu > li > a").click(function () { // bind onclick if ($(this).parent().hasClass('selected')) { $("#nav_evnavmenu .selected div div ...

Managing interactions with dynamically created buttons

Our Story Greetings! I am skilled in C# and VB.net, but I am diving into the world of Javascript and React. Currently, I am building a ticket purchase app to enhance my skills. While I was able to quickly create this app using Angular, React has posed mor ...

Retrieve the selected value from a radio button

I am attempting to display the chosen value in an input field when a radio button is selected. However, the functionality seems to be broken when I include bootstrap.min.js. You can find the code on JSFiddle. $('input:radio').click(function() ...

Utilizing Vue.js to share a single array of data across two distinct input lists

For a clearer understanding of my requirements, I have put together a demo on JSFiddle: https://jsfiddle.net/silentway/aro5kq7u/3/ The code snippet is presented below: <script src="https://cdn.jsdelivr.net/npm/vue"></script> <div id=" ...

Modifying the input's value dynamically alters the selection choices in Vuetify

Choose the First option Fpo, when you select the first item, the first object in the list is assigned to the variable test. I have used test.name as a model for that input field. Strangely, when I try to modify the input field, the select option also chang ...

trigger opening a bootstrap modal programmatically

I have a modal setup using Bootstrap with the code below: <div className="modal fade" id="exampleModal" aria-labelledby="exampleModalLabel" aria-hidden="true" > &l ...

Show categories that consist solely of images

I created a photo gallery with different categories. My goal is to only show the categories that have photos in them. Within my three categories - "new", "old", and "try" - only new and old actually contain images. The issue I'm facing is that all t ...

Guide to importing a JavaScript module using jQuery

I have been encountering an issue while loading a javascript file using jquery. The code I am working with is as follows: // file application.js $.getScript("module.js", function(data, textStatus, jqxhr) { ... }); Everything seems fine so far. However, t ...

When using Javascript's querySelector, often times it returns null

Here is the HTML code I am working with: <button class="pop-btn"> Pop </button> While I was able to style this button using CSS, I encountered a problem when trying to select it in Javascript: const Population_div_Button=document. ...

It is not possible to upload files larger than 4mb in ASP.NET MVC3

I am facing an issue with uploading files in ASP.NET MVC3 where I am unable to upload files larger than 4mb. I am currently using jquery.form.js for the file upload process and utilizing ajax to post the form to the server side. It works perfectly fine whe ...

The function of jQuery .click() not triggering on elements within msDropDown

I'm having difficulty implementing jQuery on an Adobe Business Catalyst site. The HTML snippet below shows the structure: <div class="banner-main"> <div class="banner-top"> <section class="banner"> <div class="catProd ...

When an anchor link is dynamically created, the `click()` method does not activate the click event

After creating an anchor element using the document.createElement('a') method, I encountered an issue where the click event was not being triggered as expected. To provide more context, refer to the code snippet below: var link = document.create ...

What purpose does generating a JSON file serve when invoking getStaticProps in Next.js?

Just diving into the world of Next.js. I've been going through the Next.js documentation and stumbled upon this: Next.js creates a JSON file that contains the outcome of executing getStaticProps. This JSON file is used in client-side routing via nex ...

Using JavaScript to transform base64 encoded strings into images

I'm currently working on an app using Titanium and I have a base64 string that I need to convert into an image from JSON data. Any assistance you can provide would be much appreciated. Thank you! ...

The Access-Control-Allow-Origin policy does not permit requests from applications running with an origin of null, specifically for those using a file:// URL

I am in the process of creating a webpage that utilizes jQuery's AJAX feature to fetch images from both Flickr and Panoramio. While the image retrieval from Flickr is functioning properly, I encounter an issue when attempting to use $.get(url, callba ...

When attempting to add a variable using the next() function, I encountered an error with the BehaviorSubject. The error message displayed was "this.count.next is not a function"

In my Angular service, there is a variable called count that I need to monitor for updates. Whenever this count variable is updated, I want to assign its new value to another variable in a separate component. import {BehaviorSubject} from "rxjs/BehaviorSu ...

"Authentic JavaScript Universal Time Coordinated (UTC) Date

I've been struggling to keep my dates in UTC within my JavaScript application. Surprisingly, the Date's getTimezoneOffset() method does not return a value of 0, which I expected it to do. This seems crucial for accurately converting dates between ...

Using Jquery to insert error messages that are returned by PHP using JSON

I am attempting to utilize AJAX to submit a form. I send the form to PHP which returns error messages in Json format. Everything works fine if there are no errors. However, if there are errors, I am unable to insert the error message. I am not sure why th ...

Utilizing AngularJs to differentiate between arrays and strings within an HTML template

I'm currently facing a challenge with creating a dynamic HTML template. In order to present data in a table, I need to distinguish between a regular String and an Array. Firstly, the HTML template is embedded within another template using the data-ng- ...

Facing a challenge with displaying an angularjs template within a popover

I am having trouble displaying custom HTML content in a popover when clicking on my "View" link. Although other content is rendering correctly, such as one with an ng-repeat inside it, my custom directive does not seem to be processed and displayed properl ...