简体   繁体   中英

How to access value of a key by index in an array in jQuery?

Take the example below, it's part of a json response. I want to access the "TestUser4" value of the fourth "ID". How can I achieve this with jQuery?

"UIDs": [
    {
      "ID": "TestUser1",
      "Type": "Ext"
    },
    {
      "ID": " TestUser2",
      "Type": "Int"
    },
    {
      "ID": "TestUser3",
      "Type": "Ext"
    },
    {
      "ID": "TestUser4",
      "Type": "Sys"
    }
  ]

My code is something similar to the following:

jQuery.ajax({
    type: "GET",
    dataType: "json",
    success: function( data ) {
        console.log( "ID: " + data.UIDs.ID[ 3 ].value );
    }
});

You have an array called UIDs, holding 4 unnamed objects having the attributes "ID" and "Type". To access this in javascript:

console.log("ID: " + data.UIDs[3].ID ); 

You are pretty close.. What you want to do is access ID at the third index of your UIDs array like so :

data.UIDs[3].ID

Example Use :

jQuery.ajax({
    type: "GET",
    dataType: "json",
    success: function( data ) {

        console.log( "ID: " + data.UIDs[3].ID);
    }
});

Hope this helps..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM