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

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

    I don't know if there is an existing underscore method that does this, but you can achieve the same result with plain javascript.

    Array.prototype.getIndexBy = function (name, value) {
        for (var i = 0; i < this.length; i++) {
            if (this[i][name] == value) {
                return i;
            }
        }
        return -1;
    }
    

    Then you can just do:

    var data = tv[tv.getIndexBy("id", 2)]

提交回复
热议问题