简体   繁体   English

如何在Javascript数组中读取对象

[英]How to read objects within Javascript array

I have Javascript array which contains User object. 我有包含User对象的Javascript数组。 I have created this array from modelAttribute . 我已经从modelAttribute创建了这个数组。

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

userList contains list of User objects. userList包含User对象列表。 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 . 但是我得到的是undefined值。 Initially I used Ajax call for same and it worked fine . 最初,我使用Ajax call来实现相同功能,并且效果很好。

$.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); console.log(“ userList:” + userList); gives

userList : [org.test.dto.UserDTO@11d1c59, org.test.dto.UserDTO@302f39, org.test.dto.UserDTO@16c57b1]   
var userList = '${userList}';

userList is not an array. userList不是数组。

Take out the quotes if it's supposed to render a javascript array. 如果应该呈现一个javascript数组,则将其删除。

Your if condition should probably be: 您的if条件可能应该是:

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

I see an error in your code. 我在您的代码中看到错误。 for(i=0; i < users.length;i++) is it works? for(i = 0; i <users.length; i ++)是否可行?

Used Ajax and Json for same and stored result in JS variable 使用相同的Ajax和Json并将结果存储在JS变量中

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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