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

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

    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-12-05 09:58
    Array.prototype.getIndex = function (obj) {
        for (var i = 0; i < this.length; i++) {
            if (this[i][Id] == obj.Id) {
                return i;
            }
        }
        return -1;
    }
    
    List.getIndex(obj);
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-05 10:01

    Lo-Dash, which extends Underscore, has findIndex method, that can find the index of a given instance, or by a given predicate, or according to the properties of a given object.

    In your case, I would do:

    var index = _.findIndex(tv, { id: voteID });
    

    Give it a try.

    0 讨论(0)
  • 2020-12-05 10:03

    This is to help lodash users. check if your key is present by doing:

    hideSelectedCompany(yourKey) {
     return _.findIndex(yourArray, n => n === yourKey) === -1;
    }
    
    0 讨论(0)
提交回复
热议问题