Updating JSON data post XMLHttpRequest call

Currently experiencing a puzzling moment.

I'm attempting to insert more information into my object after retrieving it from an external source (just for testing purposes, I intend to add random values).

Without further ado:

As an example, here is what my test.json file looks like:

[["month",[-150,100,0.7]]]

After obtaining the JSON file, I want it to resemble this:

[["month",[-150,100,0.7,24,24,0.5]]]

Request:

    xhr = new XMLHttpRequest();
    xhr.open('GET', '/test.json', true);
    xhr.onreadystatechange = function(e) {
      if (xhr.readyState === 4) {
        if (xhr.status === 200) {
          var data = JSON.parse(xhr.responseText);

          // Attempting to include this as an additional array
          data[0].push([24,24,0.5]);

          window.data = data;
          for (i=0;i<data.length;i++) {
            globe.addData(data[i][1], {format: 'magnitude', name: data[i][0], animated: true});
          }
          globe.createPoints();
          settime(globe,0)();
          globe.animate();
          document.body.style.backgroundImage = 'none'; // remove loading
        }
      }
    };
    xhr.send(null);

This is the hierarchy I observe using dev tools:

The data is being inserted deeper into the structure... I'm somewhat uncertain how to organize this.

(Working on a project involving the WebGL - Globe Google Project, FYI)

Is there a simpler way to handle a dataset than manually adding each value like...?

data[0][1].push(24);
data[0][1].push(24);
data[0][1].push(0.5);

Answer №1

To combine arrays, you can utilize the Array.prototype.concat method:

 var yourArray = [24,24,0.5];
 data[0][1] = data[0][1].concat(yourArray);

Another option is to use the apply method along with push:

data[0][1].push.apply(data[0][1], yourArray);

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

The Datetimepicker component outputs the date in datetime format rather than a timestamp

Currently, I am utilizing the datetimepicker JavaScript script with specific implemented logic: <script> var today = new Date(); var dd = today.getDate(); var mm = today.getMonth(); var yy = today.getF ...

Two interconnected queries with the second query relying on the results of the first

I am currently facing a challenge in my Phonegap (Cordova) application where I need to display a list of items, each requiring an additional query. Let me simplify it with an example scenario. Imagine a student can be enrolled in multiple courses and a co ...

Laravel is unable to interpret formData

I've been on a quest to find answers, but so far I'm coming up empty. I'm trying to send file input to a Laravel controller via Ajax, but it seems like the controller can't read the data at all. Here is my Ajax code: let fd = n ...

Utilizing Ajax to upload various files from separate input sources simultaneously

I want to upload multiple textual/select inputs along with two different file inputs to a PHP file using Ajax. The images from the file inputs are specific and need to be identified by their input names, so I cannot use <input type="file" multiple>. ...

Update Tagged Page with axios Integration in NextJs 13

In the latest version of NextJS 13, we have the option to revalidate tagged pages by using the fetch function. However, what if I want to use axios instead of fetch? Is there a way to set tags with axios? At the moment, the code for setting tags using fet ...

I am having trouble getting the unix timestamp to work with Meteor's API, pickadate.js

Based on the information from the API at , I have implemented the following code to retrieve a Unix timestamp based on a selected date. Initially, I configured: $('.startDate').pickadate({ selectMonths: true, selectYears: 15 ...

Transform the specifications to condense all fields containing a nested `name` key

The following data is provided: [ { "id": 123, "foo": "fooooooo", "bar": "bbbbbbarr", "recordtype": { "name": "type123", "some_field": & ...

Bizarre String Behavior in jQuery JSON Through Ajax Request

Something unusual is occurring: whenever I try to send the string "??" to the server using AJAX $.ajax({ type: 'POST', url: path, dataType: 'json', data: JSON.stringify({ text: "??" }) }); it consistently results in send ...

Error: Property id in jQuery is missing colon after it in the syntax

I have implemented jQuery to handle the action of clicking a submit button. While validating a form, I only need a single value from the form rather than all of them. Everything seems to be functioning correctly, but I am encountering an error during execu ...

Invoking a REST API in PowerShell by passing a JSON object containing an array of objects as a property

Attempting to replicate a C# class definition received in the body of a web API call using PowerShell in order to make a REST method call with that object represented as JSON. The desired JSON structure looks like this: '{ "Name" : "Test" , " ...

The error message "Json has no subscript members" is caused by the type 'Any'

Encountering a perplexing Error Issue with subscript members of type 'Any' Having trouble with 'dayZeroTemperatureMax, dayZeroTemperatureMin' lines and seeking a solution. Exhausted all online resources but nothing seems to work. He ...

The absence of the Django CSRF token has been detected

Inside the custom.js file, there is a function defined as shown below : function contactTraxio(fullname, telephone, email) { if (typeof(fullname)==='undefined') fullname = null; if (typeof(telephone)==='undefined') telephone = ...

The term "Highcharts does not exist"

I'm encountering an issue with my code: <html> <head> <title><%=sAtaskaitaTitle%></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <meta name=vs_targetSchem ...

NodeJS server connection delay

My server has an Express NodeJS instance installed. The API stops responding when it is overloaded, leading to the following response: POST /my/api/result - - ms - - I attempted the following in ./bin/www: server.on('connection', function(sock ...

The button elicited no response

Within my HTML document, I have a table implementation: <h:form id="form"> <p:dataTable id="table" styleClass="table" value="#{userMB.allAdmins}" var="admin" paginator="true" rows="15" rowKey="#{admin.id}" selection="#{userMB.user ...

Modify HTML content according to the response received from the backend

I am trying to dynamically update the text content of an HTML tag based on a response from the backend. My application is running on a Django server where I have a timer in the backend measuring the processing time. I need to send this processing time to t ...

On production, Heroku fails to load JavaScript files, only allowing CSS files to be loaded. However, the files load successfully when

I've been struggling to find a solution to my problem, so I'm reaching out for some help. I am in the process of deploying my node (express) app to Heroku, but I've encountered an issue where only CSS files from my public folder are being t ...

Tips for Resolving This Issue: Dealing with Cross-Origin Read Blocking (CORB) Preventing Cross-Origin Response

Caution: jquery-1.9.1.js:8526 The Cross-Origin Read Blocking (CORB) feature has blocked a cross-origin response from with MIME type application/json. For more details, refer to . My Code snippet is as follows: <!DOCTYPE html> <html> <hea ...

Use jQuery to extract data from the URL instead of relying on PHP

http://h3gsat.altervista.org/DettagliCompleto.php?id=4567 I attempted to extract the id parameter without success. I am attempting to accomplish this using JavaScript (jQuery) instead of PHP, but I am unsure of how to proceed. ...

Simulating Cordova plugin functionality during unit testing

I have a code snippet that I need to test in my controller: $scope.fbLogin = function() { console.log('Start FB login'); facebookConnectPlugin.login(["public_profile", "email", "user_friends"], FacebookServices.fbLoginSuccess, FacebookServic ...