Javascript 获取json数组的最后一个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37542093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the last element in json array
提问by John Wick
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.
我怎样才能在seats 对象中获取json 数组中的最后一个元素。我想获得值为 845 的 countryid,但是这个 json 是动态的,所以我想获得座椅对象中的最后一个元素。我的 api 是这样结构的。先感谢您。
{
"expirationDate":"April 21, 2017",
"remainingDays":325,
"seats":[{"activeStatus":"S","pid":"TE70","firstName":"TE70","countryid":840},
{"activeStatus":"Y","pid":"TE80","firstName":"TE80","countryid":845}]
}
回答by Mehdi
You can do this by accessing the jsonData.seats
array by index, index of the last item being equal to jsonData.seats.length-1
您可以通过jsonData.seats
按索引访问数组来完成此操作,最后一项的索引等于jsonData.seats.length-1
simply:
简单地:
var countryId = jsonData.seats[jsonData.seats.length-1].countryid
回答by iuliu.net
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