简体   繁体   中英

JSON array push array

I have a JSON structure as so:

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

I wish to append data into the "info" part of the structure. my variables look like so:

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

I have tried:

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

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

All the above have resulted in is:

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

How would I go about pushing into the "info" section of my jsonData?

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

jsonData is an array, info is not a property of the array itself, just of the first value in the array.

If you wanted to add this to each value in array you would do something like:

jsonData.foreEach(function(v){ 
    v.info = {
        ...
    }
})

Where forEach is supported on all browsers > IE8 .

You could try:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM