2014-09-24 86 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