Ajinkya
Ajinkya

Reputation: 22710

How to read objects within Javascript array

I have Javascript array which contains User object. I have created this array from modelAttribute.

var userList = '${userList}';     // userList is a spring model attribute

userList contains list of User objects. I am accessing it as

for(i=0;i<userList.length;i++)
    {
        if(searchKey == "" || userList[i].indexOf(searchKey) != -1)
        {   
            $('#userTable').dataTable().fnAddData( [
                  userList[i].firstName,
                  userList[i].lastName,
                  userList[i].institution,
                  userList[i].email] );
        }   
    }

But I am getting values as undefined. Initially I used Ajax call for same and it worked fine .

$.getJSON("lookup/users", {name:searchKey,userType:"requester"}, function(userList) {
// It works fine        
        for(i=0;i<userList.length;i++)
        {
            $('#userTable').dataTable().fnAddData( [
                  userList[i].firstName,
                  userList[i].lastName,
                  userList[i].institution,
                  userList[i].email] );
        }

    });

How can I access it now ?

EDIT:
console.log("userList :" + userList); gives

userList : [org.test.dto.UserDTO@11d1c59, org.test.dto.UserDTO@302f39, org.test.dto.UserDTO@16c57b1]   

Upvotes: 0

Views: 6249

Answers (4)

Ajinkya
Ajinkya

Reputation: 22710

Used Ajax and Json for same and stored result in JS variable

userList = null; 
    $.getJSON("lookup/users", {name:"",userType:"requester"}, function(users) {
             userList = users;
         });

Upvotes: 0

techfoobar
techfoobar

Reputation: 66663

Your if condition should probably be:

if(searchKey == "" || userList[i].firstName.indexOf(searchKey) != -1 || userList[i].lastName.indexOf(searchKey) != -1) {
    ...
}

Upvotes: 1

var userList = '${userList}';

userList is not an array.

Take out the quotes if it's supposed to render a javascript array.

Upvotes: 2

Ankun
Ankun

Reputation: 444

I see an error in your code. for(i=0; i < users.length;i++) is it works?

Upvotes: 0

Related Questions