Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the last element in json array

how can I get the last element in the json array in the seats object. I want to get the countryid of with the value of 845, however this json is dynamic so i want to get the last element in the seats object. My api is structured like this. Thank you in advance.

{
"expirationDate":"April 21, 2017",
"remainingDays":325,
"seats":[{"activeStatus":"S","pid":"TE70","firstName":"TE70","countryid":840},
        {"activeStatus":"Y","pid":"TE80","firstName":"TE80","countryid":845}]
 }
like image 497
John Wick Avatar asked May 31 '16 09:05

John Wick


3 Answers

You can do this by accessing the jsonData.seats array by index, index of the last item being equal to jsonData.seats.length-1

simply:

var countryId = jsonData.seats[jsonData.seats.length-1].countryid
like image 183
Mehdi Avatar answered Nov 05 '22 04:11

Mehdi


Try this:

var jsonObject = {
"expirationDate":"April 21, 2017",
"remainingDays":325,
"seats":[{"activeStatus":"S","pid":"TE70","firstName":"TE70","countryid":840},
        {"activeStatus":"Y","pid":"TE80","firstName":"TE80","countryid":845}]
 }

var lastElement = jsonObject.seats[jsonObject.seats.length-1].countryid
like image 24
iuliu.net Avatar answered Nov 05 '22 02:11

iuliu.net


NB: Copy of @iuliu.net's code

use DOT at

example.at(-1)

 var jsonObject = {
        "expirationDate":"April 21, 2017",
        "remainingDays":325,
        "seats":[{"activeStatus":"S","pid":"TE70","firstName":"TE70","countryid":840},
                {"activeStatus":"Y","pid":"TE80","firstName":"TE80","countryid":845}]
                 }

var lastElement = jsonObject.seats.at(-1).countryid
like image 39
Marcques Ethan Mouton Avatar answered Nov 05 '22 03:11

Marcques Ethan Mouton