find the array index of an object with a specific key value in underscore

前端 未结 12 2416
暖寄归人
暖寄归人 2020-12-05 09:12

In underscore, I can successfully find an item with a specific key value

var tv = [{id:1},{id:2}]
var voteID = 2;
var data = _.find(tv, function(voteItem){ r         


        
12条回答
  •  半阙折子戏
    2020-12-05 09:59

    findIndex was added in 1.8:

    index = _.findIndex(tv, function(voteItem) { return voteItem.id == voteID })
    

    See: http://underscorejs.org/#findIndex

    Alternatively, this also works, if you don't mind making another temporary list:

    index = _.indexOf(_.pluck(tv, 'id'), voteId);
    

    See: http://underscorejs.org/#pluck

提交回复
热议问题