Guide to converting JSON data into object structures

Question - How do I convert JSON data into objects? You can find the JSON data here

Details - After successfully connecting to the API and retrieving the JSON data, I am looking to map two arrays data.hourly.time[] and data.hourly.temperature_2m[] into a single DataTable. I require the DataTable to display the JSON data using the Google Charts API. Below is an example of the DataTable format I am aiming to create using the two arrays from the JSON data.

Javascript Code

  $.ajax({
        url: FullURL,
        dataType: "JSON",
        success: function (data) {
            
            alert(data.hourly.time[1] + "_" + data.hourly.temperature_2m[1]);
            
       // The example below is from the Google API documentation. I aim to convert the JSON array into a DataTable 
            var data = new google.visualization.DataTable();
            data.addColumn('number', 'X');
            data.addColumn('number', 'Dogs');
            data.addRows([
                [0, 0], [1, 10], [2, 23], [3, 17], [4, 18], [5, 9],
                [6, 11], [7, 27], [8, 33], [9, 40], [10, 32], [11, 35],
                [12, 30], [13, 40], [14, 42], [15, 47], [16, 44], [17, 48],
                [18, 52], [19, 54], [20, 42], [21, 55], [22, 56], [23, 57],
                [24, 60], [25, 50], [26, 52], [27, 51], [28, 49], [29, 53]
            ]);

Answer №1

To accomplish this task, you can leverage the Array.prototype.forEach() method. Here is a link to the Array.prototype.forEach() documentation on MDN.

The index of the current element can be accessed as the second argument of the callback function. This index can be used for interacting with another array.

const data = new google.visualization.DataTable();
data.addColumn('number', 'Time');
data.addColumn('number', 'Temperature');
const temperatureArray = data.hourly.temperature_2m;
data.hourly.time.forEach((currentTime, index) => {
  data.addRow([currentTime, temperatureArray[index]])
});

Answer №2

Learn how to transform JSON data into a grid structure (array of arrays) using the array method .map(). This grid can then be utilized in a datatable by calling data.addRows(grid). To simplify this demonstration, the JSON input has been condensed to only 10 items:

const input = { "latitude": 42.635273, "longitude": -73.72632, "generationtime_ms": 7.2220563888549805, "utc_offset_seconds": -18000, "timezone": "America/New_York", "timezone_abbreviation": "EST", "elevation": 35.0, "current_weather": { "temperature": -0.1, "windspeed": 3.2, "winddirection": 304.0, "weathercode": 3, "time": "2023-01-21T18:00" }, "hourly_units": { "time": "iso8601", "temperature_2m": "°C" }, "hourly": { "time": ["2023-01-14T00:00", "2023-01-14T01:00", "2023-01-14T02:00", "2023-01-14T03:00", "2023-01-14T04:00", "2023-01-14T05:00", "2023-01-14T06:00", "2023-01-14T07:00", "2023-01-14T08:00", "2023-01-14T09:00"], "temperature_2m": [-0.5, -0.8, -1.2, -1.6, -1.7, -1.6, -1.6, -1.7, -2.1, -2.2] } };

let grid = input.hourly.time.map((val, idx) => [val, input.hourly.temperature_2m[idx]]);
console.log('grid:', grid);
// data.addRows(grid);

Output:

grid: [
  [ "2023-01-14T00:00", -0.5 ],
  [ "2023-01-14T01:00", -0.8 ],
  [ "2023-01-14T02:00", -1.2 ],
  [ "2023-01-14T03:00", -1.6 ],
  [ "2023-01-14T04:00", -1.7 ],
  [ "2023-01-14T05:00", -1.6 ],
  [ "2023-01-14T06:00", -1.6 ],
  [ "2023-01-14T07:00", -1.7 ],
  [ "2023-01-14T08:00", -2.1 ],
  [ "2023-01-14T09:00", -2.2 ]
]

While adapting to functional programming, particularly using .map() instead of traditional loops like for, might require some adjustment, it ultimately enhances code efficiency and readability.

For further reading:

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

Is there a way to dynamically include a peer dependency in a file that is bundled using webpack?

I am currently developing a plugin that relies on jQuery as a peer dependency. However, when I attempt to import this plugin into my primary project (which already has jQuery installed), I encounter the following error: Module not found: Error: Can't ...

Interactive Progress Bar implemented with Jquery and AJAX

I have a current AJAX setup on my website where I submit data via AJAX and receive a response that is displayed on the screen. However, while the server is processing the response, I would like to implement a progress bar. My idea is that I can sen ...

Toggle the JavaScript on/off switch

I am attempting to create a toggle switch using Javascript, but I am encountering an issue. Regardless of the class change, the click event always triggers on my initial class. Even though my HTML seems to be updating correctly in Firebug, I consistently ...

In Three JS, shader x, y, z coordinates are based on the orientation of the object rather than the scene itself

Animating the x,y,z coordinates of vertices in a sphere-like manner with horizontal rings around the center using attributes on a THREE.Points() object has been quite intriguing. Initially, with a MeshStandardMaterial(), tilting the Points object along the ...

Updating the light and OrbitControls in three.js

I am currently utilizing threejs to showcase an object and using OrbitControls to manage the movement of the scene with my mouse. Additionally, my scene features a DirectionalLight. Initially, when the scene is rendered, the DirectionalLight illuminates m ...

Angular 2: Dealing with NaN values from Snapshot Parameters and Services

I am facing difficulties in transferring parameters from one component to another using Angular2 router and activated route. Here is my API Service: getModels(makeNiceName: string): Observable<Models> { return this.http.get(this.baseURL + mak ...

Instructions on how to log in following the acquisition of a Google reCAPTCHA V3 key

I'm trying to implement logging in my website using ajax. However, I am facing an issue where I need to generate a Google key when I click login, before actually logging in. The function I have is as follows: $('#main-login-form').on('s ...

What is the best way to display a nested JSON object structure?

{ "Title": "Jurassic Park", "Year": "1993", "Rated": "PG-13", "Released": "11 Jun 1993", "Runtime": "127 min", "Genre": "Action, Adventure, Sci-Fi", "Director": "Steven Spielberg", "Writer": "Michael Crichton, David Koepp", "Actors": "Sam ...

The v-select menu in Vuetify conceals the text-field input

How can I prevent the menu from covering the input box in Vuetify version 2.3.18? I came across a potential solution here, but it didn't work for me: https://codepen.io/jrast/pen/NwMaZE?editors=1010 I also found an issue on the Vuetify github page t ...

JQuery code causing issue with properly closing toggle menu

I am currently working on implementing a closing toggle menu for mobile devices and facing a minor issue. What I aim for is to allow users to close the toggle menu by tapping anywhere on the screen of their device while it is active. I have almost achieved ...

How to iterate and apply styles to properties of objects in an array using Vue.js?

Currently, I am working with Vue.JS and facing some challenges while outputting data using the v-for loop. My objective is to repeat a 'base' item with unique information. You can refer to the image below for better understanding. https://i.ssta ...

What is the process for embedding a NextJS app within a different website?

I'm searching for alternative methods to embed a React/NextJS application within another application. Currently, my solution involves using an iframe and specifying the source as the execution of the React/Nextjs application. I've explored diff ...

Adding Bootstrap alert messages dynamically and having them fade in and out

Is it possible to dynamically add a Bootstrap alert with a fadeIn effect and fadeOut effect on close without using jQuery fadeIn or fadeOut functions? function alert(title, text, type) { var html = $("<div class='alert alert-dismissible hide f ...

``How can I easily navigate to the top of the page when changing routes in React Router DOM v6?

What is the best way to scroll to the top when a route changes in react router dom v6? In the past, I used a solution from this StackOverflow post to make my page automatically scroll to the top every time a route changed with react-router-dom v5. However ...

Display modal within a React list

I need to display a list of items with an edit button for each item, which should trigger a modal showing the details of that specific item. Initially, I had a single modal component in the parent element and passing the visible values to the parent state ...

Direct all clients to a specific page each (where each client is represented by a SessionScoped ManagedBean)

I am managing a page with multiple users (Client 1, Client 2, ...) and I want the action of pressing the "Exit Meeting" button (Button 1) to redirect all clients to a home page (http://localhost:8080/FasMe/faces / Public / Inicio.xhtml). Each client is re ...

What is the best way to change a javascript string into HTML so that it can be shown in a form?

I am struggling to find a solution to this issue. I am fairly new to jQuery and JavaScript, so please forgive me if my question seems basic. I am trying to call a cfc (ColdFusion) using jQuery and retrieve HTML data. However, when I receive the data, it ...

Tips for preventing the inner surface from appearing transparent in WebGL

I am working with the code snippet provided below. The issue I am currently facing is that one side of the partial sphere is non-transparent, while the other side remains transparent. How should I modify the code to make both sides non-transparent? Thank y ...

Can one create a set of rest arguments in TypeScript?

Looking for some guidance on working with rest parameters in a constructor. Specifically, I have a scenario where the rest parameter should consist of keys from an object, and I want to ensure that when calling the constructor, only unique keys are passed. ...

"Experience the power of Vue.js 3 and vue-router as the @click event seamlessly refreshes the entire

Just getting started with Vue and I'm trying to figure out how to toggle the menu open/close on mobile navigation without causing the whole page to reload. Any suggestions on how to prevent that? Here's my code: <router-link to="/ " @click="t ...