Transforming JSON information for Google chart data table

I am currently working on converting JSON data into a suitable format for a Google Chart visualization:

var jsonData =  {"Battery Voltage, (A)":
                    {"2017-11-11T00:00:00.000Z":12.3,
                     "2017-11-11T00:01:00.000Z":12.35,
                     "2017-11-11T00:02:00.000Z":12.6,
                     "2017-11-11T00:03:00.000Z":12.7,
                     "2017-11-11T00:04:00.000Z":12.8},
                "Battery Current, (A)":
                    {"2017-11-11T00:00:00.000Z":1.3,
                     "2017-11-11T00:01:00.000Z":1.4,
                     "2017-11-11T00:02:00.000Z":1.5,
                     "2017-11-11T00:03:00.000Z":1.6,
                     "2017-11-11T00:04:00.000Z":1.7}};

Another way to retrieve the data is by using the following structure:

var jsonData_2 =
{"2017-11-16T00:00:00.000Z":
          {"Charge Current, (A)":0.001373312,"Battery Voltage, (V)":12.9267109178}
,"2017-11-16T00:01:00.000Z":
          {"Charge Current, (A)":0.001373312,"Battery Voltage, (V)":12.9267109178}
,"2017-11-16T00:02:00.000Z":
          {"Charge Current, (A)":0.001373312,"Battery Voltage, (V)":12.9267109178}
,"2017-11-16T00:03:00.000Z":
          {"Charge Current, (A)":0.001373312,"Battery Voltage, (V)":12.9267109178}
,"2017-11-16T00:04:00.000Z":
          {"Charge Current, (A)":0.001373312,"Battery Voltage, (V)":12.9267109178}};

The objective is to transform this JSON data into the correct representation for a Google line chart:

[
          ['Datetime', 'Battery Current, (A)', 'Battery Voltage, (A)'],
          ['2017-11-11 01:00',  1.3,      12.3],
          ['2017-11-11 02:00',  1.4,      12.35],
          ['2017-11-11 03:00',  1.5,      12.6],
          ['2017-11-11 04:00',  1.6,      12.7]
        ]

To handle two columns in the conversion process, you can modify the code as shown below:

var chartData = [];
Object.keys(jsonData).forEach(function (column) {
  var tempArr = ['Datetime', column];
  Object.keys(jsonData[column]).forEach(function (dateValue) {
    tempArr.push(new Date(dateValue));
    tempArr.push(jsonData[column][dateValue]);
    chartData.push(tempArr);
  });
});

Answer №1

In the first step, create an array consisting of the column headings...

// create chart columns
var chartCols = ['Datetime'];
Object.keys(jsonData).forEach(function (column) {
  chartCols.push(column);
});

Next, generate a unique list of dates...

// create date list
var dateValues = [];
Object.keys(jsonData).forEach(function (column) {
  Object.keys(jsonData[column]).forEach(function (dateValue) {
    if (dateValues.indexOf(dateValue) === -1) {
      dateValues.push(dateValue);
    }
  });
});

Finally, use each date to locate the value in the corresponding column, if it exists...

// create chart data
var chartData = [chartCols];
dateValues.forEach(function (dateValue) {
  var row = [new Date(dateValue)];
  Object.keys(jsonData).forEach(function (column) {
    row.push(jsonData[column][dateValue] || null);
  });
  chartData.push(row);
});

google.charts.load('current', {
  packages: ['table']
}).then(function () {
  var jsonData = {
    "Battery Voltage, (A)":
      {"2017-11-11T00:00:00.000Z":12.3
      ,"2017-11-11T00:01:00.000Z":12.35
      ,"2017-11-11T00:02:00.000Z":12.6
      ,"2017-11-11T00:03:00.000Z":12.7
      ,"2017-11-11T00:04:00.000Z":12.8}
    ,"Battery Current, (A)":
      {"2017-11-11T00:00:00.000Z":1.3
      ,"2017-11-11T00:01:00.000Z":1.4
      ,"2017-11-11T00:02:00.000Z":1.5
      ,"2017-11-11T00:03:00.000Z":1.6
      ,"2017-11-11T00:04:00.000Z":1.7}
  };

  // create chart columns
  var chartCols = ['Datetime'];
  Object.keys(jsonData).forEach(function (column) {
    chartCols.push(column);
  });

  // create date list
  var dateValues = [];
  Object.keys(jsonData).forEach(function (column) {
    Object.keys(jsonData[column]).forEach(function (dateValue) {
      if (dateValues.indexOf(dateValue) === -1) {
        dateValues.push(dateValue);
      }
    });
  });

  // generate chart data
  var chartData = [chartCols];
  dateValues.forEach(function (dateValue) {
    var row = [new Date(dateValue)];
    Object.keys(jsonData).forEach(function (column) {
      row.push(jsonData[column][dateValue] || null);
    });
    chartData.push(row);
  });

  var table = new google.visualization.Table(document.getElementById('table_div'));
  table.draw(google.visualization.arrayToDataTable(chartData));
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="table_div"></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

Unable to assign a value to a variable within a Mongoose callback function

I am struggling to comprehend why the variable "productsAvailable" still shows true even after being set to false. router.post('/api/transactions', (req, res) => { var productsAvailable = true for(var i=0; i<3; i++) { Prod ...

Importing an object into Three.js from Blender using JSON_KEYBOARD_SHORTCUT

I'm currently utilizing the Blender plugin to export JSON files, but I've encountered an issue where the texture of my object is not being exported. The materials section within the JSON file appears as follows: "materials" : [ { "DbgCo ...

Discover the method for extracting the value from an array that has been transferred from a php script

So here's the situation - I have a text file containing data. The first step is to convert the content of the text file into an array. $lines = file($filename); Next, the data is sent back to the client (the $filename is determined through ajax). ...

In React Native, the onPress handler will continue to be triggered indefinitely after 2-3 presses

import firebase from './Firebase'; import { useState, useEffect } from 'react'; import { StyleSheet, Text, View, Button, FlatList } from 'react-native'; import { TextInput } from 'react-native-web'; import { setStatu ...

Choose a country from a modal in a React application

click here for image description I need help implementing the screenshot above. My goal is to change the default country name and flag when a user clicks on the country dropdown menu. I have been using headless UI so far, but I'm struggling to figure ...

The Google Books API has encountered an authentication error with status code 401

Trying to access public data using the Google Books API locally: An error occurred with the authentication credentials. It seems that an OAuth 2 access token, login cookie, or another valid authentication credential is missing. For more information, visit ...

Does the AJAX load more feature duplicate the existing data?

I've successfully implemented a PHP code that generates JSON data from WordPress posts in the database. By using AJAX, I'm able to load this JSON on my HTML page without any issues. Now, I want to enhance this functionality by adding a "Load Mo ...

Update the page with AJAX-loaded content

I am currently utilizing a .load() script to update the content on a webpage in order to navigate through the site. This is resulting in URLs such as: www.123.com/front/#index www.123.com/front/#about www.123.com/front/#contact However, I am encountering ...

Issue encountered while retrieving information using Axios in a Vue.js application

Currently, I am in the process of developing a full stack application using Vue.js and Fastify.js (a Node framework). The Vue app is supposed to retrieve data from the API I created and display it in the browser console. However, I am encountering an issue ...

Creating a cascading layout with React Material-UI GridList

Can the React Material-UI library's GridList component be used in a layout similar to Pinterest's cascading style? I have utilized Material-UI Card components as children for the GridList: const cards = props.items.map((item) => <Card ...

Issue with Node.js MongoDb query results in the retrieval of all documents instead of the specific

Example of Json Structure: {"address": {"building": "1007", "coord": [-73.856077, 40.848447], "street": "Morris Park Ave", "zipcode": "10462"}, "borough": "Bron ...

Guide on incorporating JavaScript code within a PDF document

Looking for guidance on implementing JavaScript in PDF files I am seeking advice from those familiar with adding JavaScript actions to PDF documents, as this is a new area of exploration for me. While I have experience with JavaScript in web development, ...

Utilizing ng-repeat to iterate over a nested array

I need help figuring out how to properly loop through a JSON array and its ingredients/directions array using ng-repeat. The current method I have attempted is not working as expected. Any suggestions or advice would be greatly appreciated! Thank you. Con ...

Issues persist with debugger functionality in browser development tools following an upgrade from Angular 8 to version 15

After upgrading from Angular version 8 to version 15, I've encountered an issue where the debugger is not functioning in any browser's developer tools. Can anyone provide some insight on what could be causing this problem? Is it related to the so ...

Determining the Position of the Cursor Within a Div

When a link is clicked, a pop up is displayed. Here is the code for the pop up: <div class='' id="custom-popover"> <div class="arrow"></div> <h3 class="popover-title">Popover left</h3> <div class="pop ...

Tips for dividing the AJAX response HTML using jQuery

I have a piece of code that is functioning properly. However, I am having trouble splitting the HTML response using AJAX jQuery. I need to split it into #div1 and #div2 by using "|". Could you please provide a complete code example and explanation, as I am ...

Guide on verifying the status of a switch toggle using Selenium and C#

I am having trouble verifying the current state of a switch ('on' or 'off') using selenium. The toggle appears in the 'on' position when the webpage loads, but it affects filter results in a table when switched off. I am unabl ...

Is it better to use relative or absolute resource scripts in an AngularJS application?

My project involves building a single-page JavaScript app using AngularJS. In order to achieve this, the index.html file has a specific structure: <html> <head> <base href="/" /> ... </head> <body id="ng-app" ng-app="myAngularAp ...

Customize Your Chrome Experience: Inject an Element to Open a Hidden HTML Page within the Extension

I am currently working on a Chrome extension and I would like to add a link tag into an object, which will then direct the user to an about page stored within the extension itself. Is there a way to achieve this? Below is the code from my content.js file: ...

Creating an HTML table from JSON data using JavaScript

I recently wrote some code that reads the contents of an XML file and converts it into JSON. The JSON data is then displayed in an HTML table. Everything seems to be working fine, but there's one issue - the first row of the table always shows as "und ...