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

前端 未结 12 2399
暖寄归人
暖寄归人 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:55

    If your target environment supports ES2015 (or you have a transpile step, eg with Babel), you can use the native Array.prototype.findIndex().

    Given your example

    const array = [ {id:1}, {id:2} ]
    const desiredId = 2;
    const index = array.findIndex(obj => obj.id === desiredId);
    

提交回复
热议问题