JavaScript Dynamic Array for Generating GoogleChart JSON Data

I am attempting to create a line chart using Google Charts ( ), but I am struggling with formatting the array for the chart.

The required array format is as follows :

var data = google.visualization.arrayToDataTable([
  ['Year', 'Sales', 'Expenses'],
  ['2004',  1000,      400],
  ['2005',  1170,      460],
  ['2006',  660,       1120],
  ['2007',  1030,      540]
]);

Here is my attempt at formatting it differently :

var data = google.visualization.arrayToDataTable([['Year', 'Marque1', 'Marque2', 'Marque3', 'Marque4']]);
var i=1;
msg.forEach(function(entry) {               
    data.addRows([
      ['2004',  i-1,      0,      i,      6],
      ['2004',  i,      0,      i,      6],
      ['2004',  i+1,      0,      i,      6]
    ]);                 
    i++;
});

These values are dummy data placeholders until I can successfully create the array.

Upon running this code, I receive the following error in the browser console :

Uncaught Error: Type mismatch. Value 0 does not match type string in column index 1 

When I replace the values with strings, Google displays an error message instead of the chart :

Data column(s) for axis #0 cannot be of type string

Answer №1

Not sure if I fully understand your question, but here's a possible solution:

let carData = [];
carData.push(['Year', 'Marque1', 'Marque2', 'Marque3', 'Marque4']);
let index = 1;
messages.forEach(function(item) {
    carData.push([5, 5, 5, 5, 5]); // Insert your values here
});
let chartData = google.visualization.arrayToDataTable(carData);

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

Playing with Data in AG-Grid using Javascript

I am working on implementing data display using AG Grid with an AJAX call, but I am facing an issue where no data is being shown in the grid. Even though my AJAX call seems to be functioning correctly and returning the desired object List, the grid itsel ...

Utilizing dropdown list values within the context of $.getJSON: A practical guide

This is the script that I have written. $.getJSON("Employee.js", function (data) { var sample = data.one;alert(sample) }); Below you can see the contents of the Employee.js file: var sample={ "one":"Manager","two":"Sr.Eng","three":"Eng" } I am ...

Ways to update a component when the state changes

When attempting to access components that require authentication, I want to redirect to the login page if the user is not logged in. However, I am facing an issue with initializing the firebase auth object, as there is a small delay. The documentation sugg ...

Axios and Postman generate unique X-CSRF tokens

Why does the X-CSRF token I receive from my axios request differ from the one I get in Postman? Here is how I am retrieving it: headers: { "X-CSRF-Token": "FETCH" } Furthermore, I am unable to use the X-CSRF token from my axios request in Postman as it ...

The camera steadily advances in WebVR Cardboard using three.js technology, never stopping its forward movement

I've been experimenting with trying to create a smooth, continuous forward movement for the camera in a three.js/WebVR project, specifically with only a cardboard viewer needed. After much trial and error, I've discovered that the usual camera m ...

Unleashing the potential of Chrome's desktop notifications

After spending the past hour, I finally found out why I am unable to make a call without a click event: window.webkitNotifications.requestPermission(); I am aware that it works with a click event, but is there any way to trigger a Chrome desktop notifica ...

The slides on SlickJS are initially loaded in a vertical alignment, but once the arrows are interacted with,

I've put together a demonstration that highlights the issue I'm facing. Upon visiting the contact section, you'll notice that all the slickJS slides are stacked vertically initially, but once you interact with them by clicking on the arrow o ...

Is there a way to display the description field instead of the Id in a table using pxp-ui?

I am currently working with a table in pxp-ui and have implemented the following column: subsystemId: { type: 'AutoComplete', isSearchable: true, label: 'Subsystem Id', ...

Stop JSON.parse from shuffling the order of an object

When working on my web application, I retrieve a JSON string from the server and store it in a variable called greetings: var greetings = '{"2":"hoi","3":"hi","1":"salam"}' I have obser ...

mysterious supplier factoryprovider <- factory <- angular js controller

I'm encountering an issue with injecting dependencies from a service to a controller. Despite adding it, I keep receiving the following error: Unknown provider: websiteFactoryProvider <- websiteFactory <- listCtrl My main goal is to display ...

Transforming a JSON object retrieved from requests.get() into a dictionary

I am retrieving a JSON object from a URL: import requests r = requests.get('http://my.endpoint.com/Hardware.json') At this point, I need to convert r.json() into a dict, so that I can add it as a document to MongoDB (still learning about Mongo) ...

Utilize JSON data as a source for autocomplete in JQuery

I have encountered an issue while using the autocomplete widget of JQuery with JSON to parse database information. Despite searching for a solution, I have not been able to resolve it. Here is my PHP file with JSON parsing: The error displayed in the brow ...

JavaScript's Selenium WebDriver - Explicit Waiting

Currently, I am utilizing selenium-webdriverjs. My objective is to pause until a specific element is displayed. To accomplish this, I have implemented an explicit wait that operates effectively: var shown = false; driver.wait(function(){ driver.findEl ...

JavaScript library called "Error: JSON input ended unexpectedly"

I am currently operating a server using node.js and Express v4.0 Additionally, I am utilizing the request library. However, when receiving a response from the server, I encounter an Uncaught SyntaxError: Unexpected end of JSON input. The response I receiv ...

Iterate through all elements in Javascript/jQuery while excluding any nested children elements

Looking to retrieve all elements in the document: $("*").each(function(){ var el = $(this); }); I want to target only parent elements, excluding their children. For example: <div> <!--TARGET--> <div></div> <!--IGNORE--&g ...

Typescript versus ES5: A comparison of Node.js server-side applications written in different languages

Note: When I mention regular JavaScript, I am referring to the ES5 version of JS. As I lay down the groundwork for a new project, my chosen tech stack consists of Node.js for the back-end with Angular2 for the front-end/client-side, and Gulp as the build ...

I need to extract information from the database and save all entries from the form in order to send them to myself. This includes calculating the real-time multiplication of weight and pieces

For a project, I need to gather contact data from the client, and then populate a MySQL database with the information to create new rows in a table. There's an additional requirement where I have to calculate the total weight of element pieces multip ...

Display list items in HTML based on the length of an array

In my backend, I have a user-defined array of cars. If the user selects 3 cars, the array will contain 3 elements. I would like to display specific details of the cars in HTML elements within a list. The array is based on JavaScript. Here is an example of ...

Deciphering unique characters within JSON syntax

I am currently using NSJSONSerialization to parse JSON data. NSData *jsonData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"url"]]; NSError *jsonError = nil; id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMu ...

employing the d3.queue method to defer execution until receiving the AJAX response

Seeking examples of integrating AJAX, d3, and PHP to extract data from a database and create graphs. Any guidance would be appreciated. I am currently using d3 to generate a force chart based on database information retrieved through AJAX and PHP. I have ...