2

Possible Duplicate:
I have a nested data structure / JSON, how can access a specific value?

This is my js code for ajax call

var UserArr = new Array();
    $.ajax({
                type: 'POST',
                data: postJSONData,
                url: 'PrivateSpace.asmx/GetUserDetails',
                dataType: 'json',
                async: false,
                contentType: 'application/json; charset=utf-8',
                success: function success(response) {
                debugger;
                UserArr = response.d;


                },
                error: function failure(response) {
                    alert('failed');
                }
            });

For instance :The UserArr will be like this:

[0] will have userid: 101, username: jack
[1] will have userid: 102, username: jones

I have tried like this but it doesnt seems to work

for (var i = 0; i < UserArr.length; i++) {     


            User_ID = // i couldn get like UserArr.userid
            Name = // i couldn get like UserArr.username
     }

Kindly help me out..

Community
  • 1
  • 1
Xavier
  • 1,672
  • 5
  • 27
  • 46

3 Answers3

1

You don't access it by UserArr.userid, but by UserArr[i].userid, given that the information you've provided about how the object looks is correct.

Another way of iterating over an array, which allows you to worry less about the mechanics of the iteration, would be to use Array.forEach

UserArr.forEach(function(user) {
    alert(user.userid);
});

You would need to use a shim for older browsers, though; see the MDC fallback in this SO answer for a good fix for some browser shortcomings.

Community
  • 1
  • 1
David Hedlund
  • 128,221
  • 31
  • 203
  • 222
1

Your data looks be in the form of array of objects.. Try it this way..

User_ID = UserArr[i].userid
Name = UserArr[i].username
Sushanth --
  • 55,259
  • 9
  • 66
  • 105
1

UserArr doesn't have a userid property. Every index of the array has a userid property.

for (var i = 0; i < UserArr.length; i++) {     
    User_ID = UserArr[i].userid;
    Name = UserArr[i].username;
}
Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139