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

Preserving the button's state when clicked

Here is my code snippet: <blink> const [thisButtomSelected, setThisButtomSelected] = useState(false); var thisButton = []; const onAttributeClick = (e) => { thisButton[e.currentTarget.value] = { thisID: e.currentTarget.id, thisName: e. ...

Accessing nested objects within a JavaScript array for an Express API

My current data sample looks like this: var data = [{ articles : [{ id : '0', url : 'foo', title : 'Foo', body : 'some foo bar', category : 'foo', tags : ...

Create a dynamic dropbox using JavaScript/JQuery in an HTML page

I am currently working on implementing 3 different drop down boxes that are triggered by 4 different buttons. These drop down boxes should appear within the #apple div. When Button B1 is clicked, the drop down options include Apple, Mango, and Papaya. Whe ...

Leveraging React Hooks' useEffect to trigger a prop callback function defined with useCallback

Currently, I am working on developing a versatile infinite scrolling feature using React Hooks along with the ResearchGate React Intersection Observer. The main concept revolves around a parent passing down a mapped JSX array of data and a callback functio ...

Tips for utilizing JSON for mapping files

Hey there! I am currently developing a 2D game using libgdx and I'm in need of a method to save vertices from an editor I've been working on. My initial thought was to store everything in JSON format. { meshes: { attributes: {"POSITION", "CO ...

Retrieving JSON data from R server

I am currently exploring ways to use R to send requests to a server. While I am familiar with packages that can help with converting data to and from JSON files, I am interested in requesting specific data from a server I have configured. The server would ...

Display a loading spinner (circle) while fetching JSON data from a given URL

Just starting out with Android Studio and trying to fetch JSON data from a URL using Volley. It's all working fine, but I'd like to add a loading circle while retrieving the JSON data. If anyone could help me with my code: package imo.meteoir ...

Attempting to download an image through an axios fetch call

There is an issue I am facing while trying to retrieve an image from the website www.thispersondoesnotexit.com. function getImage() { axios({ method: 'get', url: 'https://www.thispersondoesnotexist.com/image' }) ...

Access Denied: Origin Issue with OAuth2

I am requesting an authorization code from the OAuth2 Server in order to authenticate a user with my Microsoft App. For more information, I consulted this document. This is my attempt to make the call: function httpGet(){ var theUrl = "https://lo ...

When attempting to bind various data to a single div using knockout js, the issue of duplicate records appearing arises

I am encountering an issue with a div that is set up to display 10 records at a time. When the user clicks on the next link, the next set of 10 records should be loaded from the server. However, after binding the newly added records, they are being shown m ...

Is there a way to trigger an Axios response without repeated calls or the use of a button?

As I navigate my way through using react and Axios, I encountered an issue with a get request in my code. Currently, I have a button that triggers the request when clicked, but I want to eliminate the need for this button and instead have the information d ...

Unsure about the approach to handle this PHP/JSON object in Javascript/jQuery

From my understanding, I have generated a JSON object using PHP's json_encode function and displayed it using echo. As a result, I can directly access this object in JavaScript as an object. Here is an example: .done(function(response) { var ...

Issue encountered while incorporating a PHP file into Javascript code

I'm facing a particular issue where I have a PHP file that is supposed to provide me with a JSON object for display in my HTML file. Everything seems to be working fine as I am receiving an output that resembles a JSON object. Here's the PHP file ...

Utilizing jQuery to send an Ajax GET request for a JSON file

Recently I have begun delving into the world of jQuery and Ajax, attempting to utilize both technologies to retrieve a JSON FILE. Below is the structure of the file: [ { "userId": 1, "id": 1, "title": "delectus aut autem", "completed": f ...

Retrieve deeply nested JSON objects that share a common value for a specified key

I am looking to extract all the nested JSON objects (nested dictionaries) from the given JSON data that have the same value for the account_id key. data = [ { "index": 1, "timestamp": 1637165214.7020836, &qu ...

Implementing an Asynchronous Limited Queue in JavaScript/TypeScript with async/await

Trying to grasp the concept of async/await, I am faced with the following code snippet: class AsyncQueue<T> { queue = Array<T>() maxSize = 1 async enqueue(x: T) { if (this.queue.length > this.maxSize) { // B ...

Passing all selected items from a list to the controller

I am currently facing an issue with my two multi-select lists. One list contains a full list of names while the second one holds the names that have been selected from the first list. The names are stored in a Vue array which populates the names into the s ...

How can I use conditional 'if' statements to import separate modules in Node.js ES Modules?

Recently, I tried out a tutorial that utilises CommonJS for exporting/ importing different keys depending on the environment. However, I am wondering how I can make it compatible with ES Modules import/export instead? This is the code snippet provided in ...

Tips for setting up a cleanup function in useEffect when making API calls within a context provider

Looking to showcase a list of products categorized and fetched from an API? Check out the code snippet below: const API = "https://dummyjson.com/products"; const ProductsList = () => { const { cate } = useParams(); //retrieving category fro ...

How can I implement a for loop in Node.js?

I am currently experiencing an issue with my for loop while attempting to retrieve data from MongoDB and display it in the browser. The problem is that it only iterates through once, resulting in only the first entry being output. Strangely enough, when ...