2014-09-24 93 views
1

一个数组中的匹配属性我有这样的:使用下划线找到对象

var members: [ 
{ 
    id:1, 
    user:{ 
    name: 'John Smith', 
    email:'[email protected]' 
    } 
}, 
{ 
    id:2, 
    user:{ 
    name: 'Jane Smith', 
    email:'[email protected]' 
    } 
}] 

我需要的成员对象以电子邮件为依据。

我想:

_.findWhere(members, {user.email: '[email protected]'}) 

没有运气。

+0

'{user.email ...'语法错误! – Bergi 2014-09-24 14:00:25

+0

@Bergi我知道 – Per 2014-09-24 14:03:59

回答

1

因为你不是在寻找一个简单的AFAIK属性,你不能使用findWhere。相反,你可以使用indexBy得到一个重新排列集合(好很多类似的查询)或用测试功能(适合偶尔的查询)发现:

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

console.info(_.findWhere(members, { 
    user: { 
     email: '[email protected]' 
    } 
})); // undefined 

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

console.info(
    _.indexBy(members, byEmail)["[email protected]"] 
); // Object 

console.info(
    _.find(members, function (member) { 
     return (byEmail(member) === "[email protected]");}) 
); // Object