Sam Street
Sam Street

Reputation: 306

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?

Upvotes: 0

Views: 75

Answers (2)

Kyle Needham
Kyle Needham

Reputation: 3389

You could try:

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

Upvotes: 2

George Mauer
George Mauer

Reputation: 122112

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.

Upvotes: 2

Related Questions