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

前端 未结 12 2383
暖寄归人
暖寄归人 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)]

    0 讨论(0)
  • 2020-12-05 09:40

    Keepin' it simple:

    // Find the index of the first element in array
    // meeting specified condition.
    //
    var findIndex = function(arr, cond) {
      var i, x;
      for (i in arr) {
        x = arr[i];
        if (cond(x)) return parseInt(i);
      }
    };
    
    var idIsTwo = function(x) { return x.id == 2 }
    var tv = [ {id: 1}, {id: 2} ]
    var i = findIndex(tv, idIsTwo) // 1
    

    Or, for non-haters, the CoffeeScript variant:

    findIndex = (arr, cond) ->
      for i, x of arr
        return parseInt(i) if cond(x)
    
    0 讨论(0)
  • 2020-12-05 09:40

    The simplest solution is to use lodash:

    1. Install lodash:

    npm install --save lodash

    1. Use method findIndex:

    const _ = require('lodash');

    findIndexByElementKeyValue = (elementKeyValue) => {
      return _.findIndex(array, arrayItem => arrayItem.keyelementKeyValue);
    }
    
    0 讨论(0)
  • 2020-12-05 09:41

    you can use indexOf method from lodash

    var tv = [{id:1},{id:2}]
    var voteID = 2;
    var data = _.find(tv, function(voteItem){ return voteItem.id == voteID; });
    var index=_.indexOf(tv,data);
    
    0 讨论(0)
  • 2020-12-05 09:44

    I got similar case but in contrary is to find the used key based on index of a given object's. I could find solution in underscore using Object.values to returns object in to an array to get the occurred index.

    var tv = {id1:1,id2:2};
    var voteIndex = 1;
    console.log(_.findKey(tv, function(item) {
      return _.indexOf(Object.values(tv), item) == voteIndex;
    }));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>

    0 讨论(0)
  • 2020-12-05 09:46

    If you're expecting multiple matches and hence need an array to be returned, try:

    _.where(Users, {age: 24})
    

    If the property value is unique and you need the index of the match, try:

    _.findWhere(Users, {_id: 10})
    
    0 讨论(0)
提交回复
热议问题