使用下划线在数组中查找具有对象的匹配属性

时间:2014-09-24 13:56:04

标签: javascript underscore.js

我有这个:

var members: [
{
   id:1,
   user:{
     name: 'John Smith',
     email:'john@gmail.com'
   }
},
{
   id:2,
   user:{
     name: 'Jane Smith',
     email:'jane@gmail.com'
   }
}]

我需要以电子邮件作为标准的成员对象。

我试过了:

_.findWhere(members, {user.email: 'john@gmail.com'})

没有运气。

1 个答案:

答案 0 :(得分:1)

因为您不是在寻找一个简单的属性AFAIK,所以您不能使用findWhere。相反,您可以使用indexBy来获取重新排列的集合(适用于许多类似的查找)或使用测试函数查找(适用于偶尔的查找):

// http://jsfiddle.net/tshpfz0x/3/
var members = [{
   id: 1,
   user: {
       name: 'John Smith',
       email: 'john@gmail.com'
   }
}, {
   id: 2,
   user: {
       name: 'Jane Smith',
       email: 'jane@gmail.com'
   }
}];

console.info(_.findWhere(members, {
    user: {
        email: 'john@gmail.com'
    }
})); // undefined

function byEmail(member) {return member.user.email;}

console.info(
   _.indexBy(members, byEmail)["john@gmail.com"]
); // Object

console.info(
   _.find(members, function (member) {
       return (byEmail(member) === "john@gmail.com");})
); // Object