Convert JSON data into a Google chart with a dynamic number of columns and arrays

Modify my variable chart which currently holds this JSON:

[{
    "month": "January",
    "values": [0, 0, 0, 0, 0, 0, 0, 0, 0]
}, {
    "month": "February",
    "values": [0, 0, 0, 0, 0, 0, 0, 0, 0]
}, {
    "month": "March",
    "values": [35, 3, 8, 18, 0, 0, 0, 0, 0]
}, {
    "month": "April",
    "values": [36, 1, 0, 2, 0, 0, 0, 0, 0]
}, {
    "month": "May",
    "values": [0, 0, 0, 0, 0, 0, 0, 0, 0]
}, {
    "month": "June",
    "values": [0, 0, 0, 0, 0, 0, 0, 0, 0]
}, {
    "month": "July",
    "values": [0, 0, 0, 0, 0, 0, 0, 0, 0]
}, {
    "month": "August",
    "values": [0, 0, 0, 0, 0, 0, 0, 0, 0]
}, {
    "month": "September",
    "values": [0, 0, 0, 0, 0, 0, 0, 0, 0]
}, {
    "month": "October",
    "values": [0, 0, 0, 0, 0, 0, 0, 0, 0]
}, {
    "month": "November",
    "values": [0, 0, 0, 0, 0, 0, 0, 0, 0]
}, {
    "month": "December",
    "values": [0, 0, 0, 0, 0, 0, 0, 0, 0]
}]

The values in the "values" attribute are dynamic and depend on the number of technicians in my database.

I have initialized my columns like this:

var data = new google.visualization.DataTable();
data.addColumn('string', 'Month');
var techlist = @Html.Raw(Json.Encode(ViewBag.techs));
for(var j=0; j<@ViewBag.nbTechs;j++){
    data.addColumn('number', techlist[j]);
}

So, I am wondering: How can I assign the "month" attribute to the Month column and distribute all the values in "values" across the columns I created (in the same order as they appear in "values" and matching the order of creation of number columns)?

Thank you for your assistance!

Answer №1

Below is an example of how this could be implemented...

google.charts.load('current', {
  callback: drawTable,
  packages: ['table']
});

function drawTable() {
  var jsonData =
  [{
      "month": "January",
      "values": [0, 0, 0, 0, 0, 0, 0, 0, 0]
  }, {
      "month": "February",
      "values": [0, 0, 0, 0, 0, 0, 0, 0, 0]
  }, {
      "month": "March",
      "values": [35, 3, 8, 18, 0, 0, 0, 0, 0]
  }, {
      "month": "April",
      "values": [36, 1, 0, 2, 0, 0, 0, 0, 0]
  }, {
      "month": "May",
      "values": [0, 0, 0, 0, 0, 0, 0, 0, 0]
  }, {
      "month": "June",
      "values": [0, 0, 0, 0, 0, 0, 0, 0, 0]
  }, {
      "month": "July",
      "values": [0, 0, 0, 0, 0, 0, 0, 0, 0]
  }, {
      "month": "August",
      "values": [0, 0, 0, 0, 0, 0, 0, 0, 0]
  }, {
      "month": "September",
      "values": [0, 0, 0, 0, 0, 0, 0, 0, 0]
  }, {
      "month": "October",
      "values": [0, 0, 0, 0, 0, 0, 0, 0, 0]
  }, {
      "month": "November",
      "values": [0, 0, 0, 0, 0, 0, 0, 0, 0]
  }, {
      "month": "December",
      "values": [0, 0, 0, 0, 0, 0, 0, 0, 0]
  }];



  var data = new google.visualization.DataTable();
  data.addColumn('string', 'Month');
  //var techlist = @Html.Raw(Json.Encode(ViewBag.techs));
  for(var j=0; j<jsonData[0].values.length;j++){
    data.addColumn('number', 'col' + j);
  }

  jsonData.forEach(function(row, index) {
    var currentDate = new Date();
    var rowData = [];
    rowData.push(row.month);
    if (currentDate.getMonth() >= index) {
      rowData = rowData.concat(row.values);
    } else {
      row.values.forEach(function() {
        rowData.push(null);
      });
    }
    data.addRow(rowData);
  });

  var visualization = new google.visualization.Table(document.getElementById('table'));
  visualization.draw(data, {});
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="table"></div>

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

What is the best way to save the result of an API request as an object or convert an array into JSON format?

My app is attempting to make an API call and display the retrieved data in a modal. The issue lies in storing the API response as an array, which prevents me from accessing its sub-elements effectively. My query is: Is there a way to either: Save an obje ...

When validated, the Yup.date() function seamlessly converts a date into a string without including the timezone

Currently, I am integrating Yup with react-hook-form and have defined the following schema in Yup: const validationSchema = Yup.object({ installation: Yup.string().nullable().required("Required"), from_date: Yup.date() .max(new Date(), "Can ...

Creating a custom script for a search field that retrieves information from an XML document

Attempting to create a script that iterates through an XML file, the provided code currently displays alerts but fails to show information when a valid value is entered into the search field. However, upon removing the error checks and keeping the final ...

Error: An anomaly token was encountered while deploying a Laravel/Vue project using the pipeline yml in Yarn Run

I have encountered a challenge while trying to deploy my project to a server using bitbucket-pipeline with a .yml script. The project consists of a Laravel backend with PHP 7.4 and a Vue Js frontend. The issue arises during the frontend build process with ...

Unraveling JSON with Swift 4

Could anyone assist me in identifying what's causing the issue with this code? My goal is to extract JSON data from the server and store the values into variables. Upon running the code, no errors are displayed. However, when I attempt to print(users) ...

Issue with image magnification on Internet Explorer 9 using the Cloud Zoom plugin extension for Joomla

Recently, I've been utilizing a Joomla plugin called cloud zoom to enhance our gallery by providing an image magnification effect when hovering over the large image. You can see it in action on this link here. While it works flawlessly on most browser ...

Conceal/Inactivate element when scrolling, and once scrolling comes to a halt, reveal it once more

I have been working on creating a div tag to overlay an embed tag and added some javascript to prevent users from right-clicking to download the pdf inside the embed tag (even though it may seem unnecessary, it was requested by my customer). Here is the ma ...

Passing the onChange event in React to a nested child component

The code snippet below illustrates a scenario where the user encounters an error: import React from 'react'; import {render} from 'react-dom'; import Form from './form.jsx'; import axios from 'axios'; class App e ...

The art of sweet redirection with Sweetalert2

I am working on a PHP page where users can input a number in a text field. If the entered number exceeds their available credit, I need to display an error message. Upon clicking the submit button to send the form, the user is directed to makeTransfer.php ...

Can I use Javascript to access a span element by its class name?

Similar Question: How to Retrieve Element By Class in JavaScript? I am looking to extract the text content from a span element that does not have an ID but only a specific class. There will be only one span with this particular class. Can anyone guide ...

Most Effective Method for Switching CSS Style Height from "0" to "auto"

After coming across a question with no answer that suited my needs, I decided to share the solution I created. In my case, I had a hidden generated list on a page which was initially set with a CSS height of "0" and then expanded upon clicking by transit ...

Utilizing JSON data to create dynamic HTML content for Isotope.js filtering

UPDATE: After struggling to understand the previous answers, I have revised this question for clarity. As a beginner, I hope this simplified version can benefit others like me... I want to utilize isotope.js to showcase specific data from a JSON source (r ...

Is there a way to update an array within my class and access its updated output from outside the class?

let arr = [] class Test extends React.Component { handleConvertString = (event) => { let str = this.inputRef.value; let solutions = ['abb','klopp','lopp','hkhk','g','gh','a&apo ...

Collaborate and reuse Typescript code across various Node projects

Imagine we have a project structured like this: webapps ProjectA SomeClass.ts Package.json ProjectB SomeClass.ts Package.json Common LoggingClass.ts Package.json The Common "LoggingClass" needs to import a module from NPM. Let's say that ...

Encountering [object, Object] while attempting to display JSON object retrieved from req.body in the console

While attempting to insert a product's details into my API's PostgreSQL database using Postman, I encountered an issue where the values of the specs key were displayed as [object Object] instead of showing the complete data. As a result, even in ...

Why does my console refuse to log the input entered for the search?

Looking to become proficient in web development, I am attempting to record HTML search queries in the console after storing them in a variable. However, when I try running the search procedure, nothing seems to be displaying in my browser's inspect co ...

Unable to perform multi-delete action upon clicking the checkbox button as intended

Within my GridView, I have implemented a Multi-delete feature. Below is the code snippet for your reference:- <script type="text/javascript> function ValidateAll() { var chkselectcount = 0; var gridview = document.getElementById( ...

Visualize data from ajax call in tabular format

I want to display the results of an SQL query in a table using AJAX. I have written code that executes the query during the AJAX call, but when I try to display these values in a table, it shows null values on the div tag. What could be the reason for this ...

What factors should I consider when choosing the appropriate socket for receiving messages from a RabbitMQ queue?

I have encountered an issue while trying to connect to a queue on a remote server using Rabbit.js. Every attempt to connect results in the following error message: Error: Channel closed by server: 406 (PRECONDITION-FAILED) with message "PRECONDITI ...

Perform an action in jQuery when a class is modified

I am trying to create an event that will trigger when a specific element receives a class, and also when that class is removed. For example: <button id="my_butt_show">showtime</button> <button id="my_butt_hide">hide me</button> &l ...