2014-01-09 51 views
4

我無法弄清楚如何在使用_.findWhere函數時在underscore.js中動態地設置屬性。如何在使用underscore.js findWhere函數時使用變量作爲屬性名稱?

下面是該函數的文檔:造型在文檔的例子

findWhere_.findWhere(list, properties) 

Looks through the list and returns the first value that matches all of the key-value pairs listed in properties.

If no match is found, or if list is empty, undefined will be returned.

_.findWhere(publicServicePulitzers, {newsroom: "The New York Times"}); 
=> {year: 1918, newsroom: "The New York Times", 
reason: "For its public service in publishing in full so many official reports, 
documents and speeches by European statesmen relating to the progress and 
conduct of the war."} 

,我想設置的屬性搜索動態:

var publicServicePulitzers = [ 
    {"newsroom":"The New York Times", "year":2013 }, 
    {"newsroom":"The Los Angeles Times", "year":2012 } 
]; 

var myprop = 'newsroom'; 
_.findWhere(publicServicePulitzers, { myprop : "The New York Times"}); 

的結果是不確定的。

我也試過:

_.findWhere(publicServicePulitzers, {eval(myprop): "The New York Times"}); 

錯誤消息語法錯誤:缺少:物業編號後

我怎樣才能做到這一點?

感謝您的任何幫助。

回答

6

只是想通了。第二個參數找到有一個對象。因此先創建對象並將其傳遞給函數:

var myprop = 'newsroom'; 
var value = 'The New York Times'; 
var search_obj = {}; 
search_obj[myprop] = value; 

var result = _.findWhere(publicServicePulitzers,search_obj); 

Works!

+0

對,但請記住,'findWhere'實際上只是一個變相的'find'調用,所以爲單個值構建'search_obj'對你來說並沒有那麼重要(或者可能取決於你的口味: )。 –

相關問題