How can I add labels to dataPoints chart in JavaScript?

I have data from a database that I want to use to create a chart with labels and values. I have already converted the data to a JSON object. Here is the basic script for setting the labels:

<script>
    window.onload = function () {
        var arrchartdata = JSON.parse('<?php print $a;?>');

var options = {
    animationEnabled: true,
    title: {
        text: "GDP Growth Rate - 2016"
    },
    axisY: {
        title: "Growth Rate (in %)",
        suffix: "%",
        includeZero: false
    },
    axisX: {
        title: "Countries"
    },
    data: [{
        type: "column",
        yValueFormatString: "#,##0.0#"%"",
        dataPoints: [
        // Loop through the array of data to set labels and values
        ]
    }]
};
$("#chartContainer").CanvasJSChart(options);

}
</script>

I am trying to loop through the data to set the label as "arrchartdata[0].MenuName" and the value as 10.09, but I am encountering errors. Any assistance on how to properly do this looping would be greatly appreciated!

Answer №1

To incorporate the loop outside of options, first save the results in a variable and then refer to that variable within options as demonstrated below.

The data has been stored in the dataPoints variable.

var dataPoints = [];

for (var i = 0; i <arrchartdata.length ; i++) {
    console.log(arrchartdata[i].MenuName);
    dataPoints.push({label : arrchartdata[i].MenuName});
}

var options = {
    animationEnabled: true,
    title: {
        text: "GDP Growth Rate - 2016"
    },
    axisY: {
        title: "Growth Rate (in %)",
        suffix: "%",
        includeZero: false
    },
    axisX: {
        title: "Countries"
    },
    data: [{
        type: "column",
        yValueFormatString: "#,##0.0#"%"",
        dataPoints: dataPoints
    }]
};
$("#chartContainer").CanvasJSChart(options);

}
</script>

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

Error: Circular reference detected in JSON during POST request

Trying to make a POST call using JsonApi with the following example: { "data": { "attributes": { "booked_by_patient": true, "class": "PUBLIC", "descripti ...

Utilize unshift() method in JavaScript to insert form input into an array

I'm having trouble with adding elements to an array using a form and the unshift() method. The code snippet provided below isn't functioning as expected, and I need help understanding why. <form> <input id="input"></input> < ...

Diagnosing Issues with Yii2's $(document).ready Function

AppAsset: public $js = [ 'plugins/jquery/jquery.min.js', 'plugins/jquery/jquery-migrate.min.js', 'app.js', ]; When I write this in a view file: $script = <<< JS jQuery(document).ready(function( ...

Executing Scripts within the Browser: A Guide to Using Selenium

One of my current objectives involves running a script on my Selenium browser that establishes a variable and then using DevTools to access this variable in the console log. Below is the conflicting script that I am encountering issues with: from selenium ...

Change a CSV document into JSON format by transforming one of the fields into an array

Currently, I am in the process of compiling some data into a csv file with the goal of later converting it into a json object. Here is a glimpse of what a few rows of my data look like (the first row represents the header with column titles) Scientifi ...

What makes .html effective while innerHTML or appendChild do not have the same impact?

Currently, I am facing a challenge where I am attempting to incorporate an ajax response into a div that contains HTML code involving tables, forms, and more. After testing in Firefox, the innerHTML method worked flawlessly. However, Internet Explorer pre ...

Changing the values of an array to strings using javascript

I am trying to work with an array that contains elements [ABC, QWE, XYZ]. How can I convert it to ['ABC', 'QWE', 'XYZ']? When attempting to manipulate values within the current array, I encounter the following error: Referenc ...

Arduino encounters a return code of -2 in making an HTTP request through a 4G connection, using ArduinoHTTPClient and a GSM

In the process of developing a system, I have an Atmega328 functioning as a gateway to receive data from a sensor via NRF24L01 and then send it to an HTTP server in Spring through 4G connectivity. Everything was running smoothly until yesterday when I made ...

Utilize dojo to manually trigger a window resize event

Is there a way to manually trigger the window resize event (the one that occurs when you resize your browser window) using Dojo? I need this functionality to dynamically resize my C3 Charts. I came across the on module in Dojo, which allows for listening ...

How to implement a service function to handle $http responses in a controller

Is it possible to use $http only for my service and not the controller? I am getting undefined in my console.log when trying to display data in a $scope. Here is my code: app.controller('adminControl', ['$scope','$routeParams&apo ...

Is it possible to define a shared function for enums in TypeScript?

I have created an enumeration called VideoCategoryEnum: enum VideoCategoryEnum { knowledge = 0, condition = 1, interview = 2, speech = 3, entertainment = 4, news = 5, advertisement = 6, others = 7, } I am looking to implement a shared met ...

The Google Docs viewer is displaying an empty screen

I have been utilizing the Google Docs viewer on my website: <div class="embed-r embed-responsive-a"> <iframe class="embed-responsive-it" src="https://docs.google.com/viewer?embedded=true&amp;url=http://LINK.PDF"></iframe> </div& ...

Encountering a JSON parse error while utilizing the getJSON function

First time delving into coding with JavaScript and JSON, encountering an error message when using getJSON: parsererror SyntaxError: JSON.parse: unexpected character at line 2 column 1 of the JSON data return window.JSON.parse( data ); Below is my code ...

Top method for verifying input during keyup or blur events

When it comes to validating user inputs, I often find myself wondering about the best approach to take. In this case, I have created a regex for numbers with decimal points. .ts part checkIsNumber(event) { console.log('event', event.target. ...

In JavaScript, I am looking to duplicate an image and place it back at its original location after it has been moved from its initial position

I am working with 3 draggable images and my objective is to ensure that each image returns to its original position when moved. Ultimately, I want the user to be able to interact with multiple instances of images 1, 2, and 3 on the page, all of which are d ...

Looking to loop through a JSON file in PHP in order to input its contents into a table. Need assistance with iterating through each subarray. Any help would be greatly appreciated

Trying to traverse JSON arrays to extract data and upload it to a SQL server has been my recent challenge. After scouring through numerous articles online, I managed to recursively print out the data but got stuck on how to store the values in a variable ...

Error: Node.js exceeds maximum call stack size while inspecting an objectlogging or debugging

After defining a class as shown below, I encountered an error stating RangeError: Maximum call stack size exceeded when attempting to review the properties of the Object. var Individual = (function () { function Individual(name, age) { this.na ...

Spin a vector using a perpendicular in Three.js

I need help with vector rotation in Three.js {x: 0, y: 0, z: 1} I also have a normal vector: {x: 1, y: 0, z: 0} How can I rotate the first vector based on the direction of the normal to achieve this result? {x: 1, y: 0, z: 0} Your assistance in this ...

What is the best way to close ngx-simple-modal in angular7 when clicking outside of the modal component?

Can anyone help me with closing the modal in my angular7 app when the user clicks outside of the modal component? I have been using the ngx-simple-modal plugin, and I tried implementing the following code: this.SimpleModalService.addModal(LinkPopupCompone ...

Ensure that the loader remains visible until all data has been successfully retrieved from the AngularJS service

Currently, I am facing an issue with the implementation of angularjs ui-router for state transitions along with a loader assigned to each view. The problem arises when moving from one state to another and the loader disappears before all the content from t ...