我有这个:
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'})
运气不好。
最佳答案
因为您不是在寻找简单的属性,所以您不能使用 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
关于javascript - 使用下划线在数组中查找与对象匹配的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26018766/