Adding an array to a JSON array

I am trying to insert additional data into a JSON structure. Here is the current structure:

[
    {
        "name": "Sam",
        "ride": "My Ride test",
        "session": "6htbgumjtmnxko6r",
        "info": null
    },
]

The variables I have are as follows:

var jsonData = [{                                   
    "name": "Sam",                                  
    "ride": "My Ride test",                         
    "session": session,                             
    "info": null
}];
jsonData.info = [];

I have attempted the following methods:

jsonData.info.push({
        id: integer, 
        data:   { 
            distance: currentDistance || 0,
            lat: lat, 
            lon: lon
            } 
});
    jsonData.push(jsonData.info);

jsonData[3].push(jsonData.info);

However, the result has not been successful:

[
    {
        "name": "Sam",
        "ride": "My Ride test",
        "session": "6htbgumjtmnxko6r",
        "info": null
    },
    [
        {
            "id": 1,
            "data": {
                "distance": 0,
                "lat": 53.6419743,
                "lon": -1.7945115999999999
            }
        }
    ]
]

Can someone provide guidance on how to properly add data to the "info" section of my jsonData?

Answer №1

jsonData[0].details = {
    id: integer, 
    data:   { 
        distance: currentDistance || 0,
        lat: lat, 
        lon: lon
        } 
}

jsonData is an array, details is a property specific to the first value in the array, not the entire array itself.

If you wanted to add this detail to every value in the array, you would need to use a loop, like so:

jsonData.forEach(function(value){     
    value.details = {
        ...
    }
})

You can check browser compatibility for forEach here, supported on all browsers above IE8.

Answer №2

One possible solution is as follows:

jsonData[0].info = {
        id: integer, 
        data:   { 
            distance: currentDistance || 0,
            lat: lat, 
            lon: lon
        } 
}

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

When attempting to use the search bar to filter in ReactJs, an error occurs: TypeError - Unable to access properties of undefined (specifically 'filter')

When I receive data from my JSON server on the console, everything looks good. But when I try to type something in order to filter it, an unhandled error occurs with the message: 1 of 1 Unhandled Error Unhandled Runtime Error: TypeError: Cannot read prop ...

The scrolling feature in the option list for Adobe Air Client and Javascript appears to be non-functional

I am currently utilizing Air Client in conjunction with HTML, CSS and Javascript. My goal is to enable scrolling through the option list using the up and down arrow keys. However, I have encountered an issue where the scrollbar does not scroll all the way ...

After the array is printed, the foreach loop is failing to function as expected

I attempted to loop through the given array. Array ( [mech_info] => Array ( [make] => Amaka [0] => Array ( [year] => 2001 [model] => Array ...

Tips for transferring information from one php page to another php page via ajax

I am attempting to retrieve data from one PHP page and transfer it to another page through the use of Ajax. JavaScript : $.ajax({ url: "action.php", success: function(data){ $.ajax({ url: "data.php?id=data" ...

Error Alert - Troubleshooting AJAX JSON Parsing Issue

I've encountered a problem with AJAX that involves parsing a JSON Array from a webservice I am developing. The front-end of my project uses a simple combination of ajax and jQuery to showcase the results retrieved from the webservice. Despite being c ...

Converting a Pandas DataFrame to JSON converts the index into dot notation

I am facing an issue with converting a Pandas DataFrame into JSON. The to_json() method works fine, but it changes the DataFrame index to strings (e.g. 0 is converted to "0.0") instead of just "0". This is not the desired outcome for me. The DataFrame is ...

sending data in JSON format from ASIHTTPRequest to Django

Hi everyone, I've reached a dead end in my search for answers on other threads, so I'm turning to this platform for help with my question. As a beginner, I hope you can bear with me if I've made any mistakes along the way. The more I read, t ...

How to locate the position of a specific word on a webpage using jQuery

In my div, I am struggling to search like an editor. Despite multiple attempts, I have not found a solution yet. Can someone please advise me on how to resolve this issue? <div id="content"> <p> Lorem Ipsum is simply dumm ...

The function WebGLRenderer() from three.js allows for rendering in

When initializing the WebGLRenderer, I am passing in a canvas DOM element like shown below: var jqc = $('#myCanvas'); //accessing canvas with jQuery; var par = {canvas:jqc.get()}; //creating parameter object with canvas DOM element var renderer ...

Successfully extracting partial JSON data from logs using Fluentd

I am receiving data from syslog protocol in fluentd, but the format of the line is not completely compliant with syslog standards. 142>May 31 16:22:56 haproxy[77]: {"ident":"haproxy","client_ip":"172.20.1.3"," ...

What is the best way to find out which tab is currently active?

Struggling with Bootstrap 5, I found it challenging to retrieve the activated tab. Even after consulting their documentation, I only managed to obtain the ID of the first button and nothing more. var tabEl = document.querySelector('button[data-bs-t ...

Struggling with PHP's inability to decode GET parameters containing double quotes?

I am sending a 'data' parameter to a PHP page using AJAX. The parameter is in the form of a JSON string like: {"type":"value"} When I use the encodeURIComponent JS function, it converts to: %7B%22type%22%3A%22value%22%7D If I manually input i ...

Adjust the maximum and minimum values on a dual thumb slider

I have implemented a two thumb range slider to define the maximum and minimum values. However, I recently discovered that it is possible for the thumbs to cross over each other - the max value can exceed the min value and vice versa. I am looking for a s ...

Creating a filtering mechanism in C# for ActionResults by utilizing either an array or

Feeling like I'm close to a breakthrough, but still struggling with MVC5 C# webapp. I've received some helpful advice, but I just can't seem to find the exact syntax I need to get the result I want. In my controller, I'm attempting to ...

PHP code to update elements in one array based on matching keys in another PHP array

I have 2 arrays Array ( [0] => company [1] => companyid ) Array ( [company] => shops ) Looking to transform the first array into this: Array ( [0] => shops [1] => companyid ) Despite trying various bu ...

Troubleshooting problem with AngularJS ng-repeat

Seeking assistance with an angularjs issue as a newcomer to the platform. Building a photo gallery where the initial page displays thumbnail photos from twitter and instagram using ng-repeat loop. Hovering over an image fades it out, revealing a button f ...

Tips for utilizing IS NOT NULL in Knex JS

Currently, I am attempting to construct a query in knex that resembles the following: SELECT * FROM users group by users.location having users.photo is not null In my code, this translates to: knex("users").groupBy("users.location").having("users.photo" ...

Vue.JS: The central layout element and navigation system

I have a primary layout component (consists of a fixed top header and a left side menu with multiple links created using the router-link component) as well as a "dynamic" layout component that serves as the heart of the page. My goal is to change the cen ...

Tips for Adding Items to an Infinite Loop

Could you please review This Demo and advise me on how to continuously load items into the ul list in an endless manner? Currently, I have this code set up to display the list but I want it to keep adding new items to the end every time. var item = $(". ...

What steps do I need to take to have Greasemonkey execute a function upon the completion of an AJAX call

Whenever I select the trending tab on YouTube, an AJAX call is triggered to retrieve the latest trending videos. I have developed a custom script that filters out any videos I have already watched. Although this script successfully applies to the homepag ...