John Wick
John Wick

Reputation: 509

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}]
 }

Upvotes: 16

Views: 82691

Answers (5)

Allison
Allison

Reputation: 2326

For anyone looking to do this in JSONPath syntax, you can do this with $.seats[-1:]. If you wanted to do something like get the countryid attribute nested in the last element, it would be $.seats[-1:][countryid].

This is handy for chaining requests when testing endpoints in an API Client.

Upvotes: 1

Nabi K.A.Z.
Nabi K.A.Z.

Reputation: 10704

You can reverse array and then get first element: el.reverse()[0]

For your example:

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},
  ]
}

console.log( jsonObject.seats.reverse()[0].countryid ); //845

Upvotes: 1

Marcques Ethan Mouton
Marcques Ethan Mouton

Reputation: 41

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

Upvotes: 3

Mehdi
Mehdi

Reputation: 7403

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

Upvotes: 46

iuliu.net
iuliu.net

Reputation: 7145

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

Upvotes: 2

Related Questions