2015-09-09 26 views
-1

我有一個對象,其屬性爲sizeitem。並且我想在對象數組中搜索,如果匹配,它應該使用underscore.js返回id在數組中循環並返回標識使用underscore.js

例如,Size=largeitem= abcd

`Array=[ 
object:size=medium item=xyz id=1, 
object:size=Large item=sdf id=2, 
object:size=large item=abcd id=3 
]` 

我怎麼能提前返回或得到儘可能ID = 3個

謝謝! 我的問題是關於對象

+2

本網站不是讓其他人免費爲您做所有工作的地方。你需要自己處理代碼,然後當你遇到一個問題,你不能在網上進行研究後通過,那麼你應該問這裏。 – forgivenson

+0

查看http://underscorejs.org/#find – Lee

+0

這是一個關於下劃線的問題..不是我期待的工作..我正在學習它.. – rUI7999

回答

0
//initialize array 
a = [{ size: 'medium', item: 'foo', id: 1}, {size: 'large', item: 'foo', id: 2}] 

// helper method, if element found it returns its id, null otherwise 
function idFinder = function(size, item) { 
    var el = _.find(a, function(element) { return (element.size === size) && (element.item === item); }) 
    if (element) { 
    return element.id; 
    } 

    return null; 
} 

//samples 
idFinder("medium", "foo"); // will return 1 
idFinder("medium", "bar"); // will return null 
idFinder("large", "foo"); // will return 2 
+1

儘管知道'_.find'顯然非常有用,但實際上當我們有'_.findWhere'時,並不需要寫所有這些。 –