【问题标题】:Get the last element in json array获取json数组的最后一个元素
【发布时间】:2016-09-29 06:04:42
【问题描述】:

如何获取席位对象中 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}]
 }

【问题讨论】:

  • 你试过用length - 1索引吗?
  • 是的,我试过了,但我想不通。感谢您的回复。

标签: javascript arrays json


【解决方案1】:

你可以通过索引访问jsonData.seats数组来做到这一点,最后一项的索引等于jsonData.seats.length-1

简单地说:

var countryId = jsonData.seats[jsonData.seats.length-1].countryid

【讨论】:

    【解决方案2】:

    试试这个:

    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
    

    【讨论】:

    • 虽然返回未定义:/
    • 这两个语句本身返回 undefined 因为它们只是变量的声明。您需要访问lastElement 变量来获取值。
    【解决方案3】:

    我使用了上面的建议,并在 GSON lib 的循环 JsonElement 对象中使用了它。以防万一有人在寻找我所做的事情。

             for (JsonElement obj : entries){
                 
               //Do your stuff
                
               if (entries.get(entries.size() - 1).equals(obj)){
                  //Do stuff if your in last position of the jsonarray array
               }else{
                  //Do stuff until you reach the last position
               }
               
             }
    

    【讨论】:

      【解决方案4】:

      注意:@iuliu.net 的代码副本

      处使用 DOT

      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
      

      【讨论】:

        猜你喜欢
        • 2020-06-15
        • 2017-08-27
        • 2022-09-29
        • 2017-11-08
        • 1970-01-01
        • 1970-01-01
        • 2021-10-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多