如何检查Javascript数组中是否存在属性值?

时间:2016-05-26 09:44:59

标签: javascript arrays model-view-controller types indexof

我有一个类型化对象数组,它们从控制器传递到我的视图中。要求是检查字符串值是否与该数组中的任何AdminEmailAddress字符串类型对象匹配。

我尝试过使用if condition创建currentUserEmail以检查字符串indexOf是否与该列表中的任何管理员电子邮件匹配。

但脚本打破了if条件:

 if (adminUserList.AdminEmailAddress.indexOf(currentUserEmail) > -1)

我还在currentUserEmail字符串和adminUserList数组上发出警告,这些字符串都填充了数据。

运行时adminUserList的内容如下所示:

var adminUserList = [{"AdminID":1,"AdminDisplayName":"brianb","AdminEmailAddress":"brian@test.com"},{"AdminID":2,"AdminDisplayName":"wendy","AdminEmailAddress":"wendy@test.com"}];

问题:

如何检查字符串是否与数组中的属性值匹配?

代码:

包含AdminEmailAddress属性的列表类型 -

List type public class AdminUsers
{
    public int AdminID { get; set; }
    public string AdminDisplayName { get; set; }
    public string AdminEmailAddress { get; set; }

}

从Controller传递到View的列表:

List<AdminUsers> adminList = sqlConnection.GetAdminUsers();
ViewBag.AdminUserList = adminList;

包含if condition的脚本:

<script>

    var currentUserEmail = '@ViewBag.CurrUserEmail';
    var adminUserList = @Html.Raw(Json.Encode(ViewBag.AdminUserList));


    $(document).ready(function () {

        var historyTable = $('#table').DataTable({
            "order": [[6, "desc"]]
        });


        if (adminUserList.AdminEmailAddress.indexOf(currentUserEmail) > -1)
        {
            historyTable.columns([9]).visible(false);
        }



    });
</script>

3 个答案:

答案 0 :(得分:1)

使用以下功能:

function checkEmailExists(currentUserEmail){

        var match = false;
        for(var i=0;i<adminUserList.length;i++){
            if(adminUserList[i]["AdminEmailAddress"].indexOf(currentUserEmail) > -1){
                match = true;
                break;
            }

        }

        return match;
    }

答案 1 :(得分:1)

假设以下情况:

var adminUserList = [{"AdminID":1,"AdminDisplayName":"brianb","AdminEmailAddress":"brian@test.com"},{"AdminID":2,"AdminDisplayName":"wendy","AdminEmailAddress":"wendy@test.com"}];
var currentUserEmail = 'wendy@test.com';

然后您可以使用filter查找元素:

var matchArray = adminUserList.filter(function(element){
  return element.AdminEmailAddress === currentUserEmail;
})
alert(matchArray.length > 0);

这样您还可以访问实际结果:

if(matchArray.length > 0) {
    alert(matchArray[0].AdminDisplayName)
}

答案 2 :(得分:1)

您可以使用find函数find数组的元素:

var adminUserList = [{"AdminID":1,"AdminDisplayName":"brianb","AdminEmailAddress":"brian@test.com"},{"AdminID":2,"AdminDisplayName":"wendy","AdminEmailAddress":"wendy@test.com"}];

var mailToCheck = 'wendy@test.com'

var adminFound =  adminUserList.find(function(admin){ return admin.AdminEmailAddres === mailToCheck});

如果找到用户,将返回用户,否则adminFound将为undefined

但为什么要在前端呢? 浏览器中提供的用户数据,我认为不是一个好习惯。 我建议你在后端执行此操作并返回真/假响应。