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

前端 未结 12 2387
暖寄归人
暖寄归人 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条回答
  •  -上瘾入骨i
    2020-12-05 09:49

    If you want to stay with underscore so your predicate function can be more flexible, here are 2 ideas.

    Method 1

    Since the predicate for _.find receives both the value and index of an element, you can use side effect to retrieve the index, like this:

    var idx;
    _.find(tv, function(voteItem, voteIdx){ 
       if(voteItem.id == voteID){ idx = voteIdx; return true;}; 
    });
    

    Method 2

    Looking at underscore source, this is how _.find is implemented:

    _.find = _.detect = function(obj, predicate, context) {
      var result;
      any(obj, function(value, index, list) {
        if (predicate.call(context, value, index, list)) {
          result = value;
          return true;
        }
      });
      return result;
    };
    

    To make this a findIndex function, simply replace the line result = value; with result = index; This is the same idea as the first method. I included it to point out that underscore uses side effect to implement _.find as well.

提交回复
热议问题