【问题标题】:find the array index of an object with a specific key value in underscore在下划线中查找具有特定键值的对象的数组索引
【发布时间】:2014-02-07 15:07:35
【问题描述】:

在下划线中,我可以成功找到具有特定键值的项目

var tv = [{id:1},{id:2}]
var voteID = 2;
var data = _.find(tv, function(voteItem){ return voteItem.id == voteID; });
//data = { id: 2 }

但是我如何找到该对象出现在哪个数组索引处?

【问题讨论】:

标签: javascript underscore.js


【解决方案1】:

findIndex 在 1.8 中添加:

index = _.findIndex(tv, function(voteItem) { return voteItem.id == voteID })

见:http://underscorejs.org/#findIndex

或者,如果您不介意制作另一个临时列表,这也可以:

index = _.indexOf(_.pluck(tv, 'id'), voteId);

见:http://underscorejs.org/#pluck

【讨论】:

  • 我不确定下划线,但在 lodash 中你不需要匿名函数,只需 index = _.findIndex(tv, {id: voteID}) 就可以工作,如果 tv 集合具有更复杂的值(不仅仅是id 属性)
  • 只是使用 pluck 的一点要慢得多。我因为它的额外遍历。 jsperf.com/compare-find-index
【解决方案2】:

Lo-Dash扩展了Underscore,有findIndex方法,可以找到给定实例的索引,或者通过给定谓词,或者根据给定对象的属性。

在你的情况下,我会这样做:

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

试一试。

【讨论】:

  • findIntex 这是一个来自 lo-dash 的方法,而不是来自下划线
  • @WallyssonNunes 这正是我写的——“Lo-Dash,它扩展了 Underscore,有 findIndex 方法”
  • 这现在是标准下划线库的一部分,从 1.8.0 版开始:underscorejs.org/#1.8.0
【解决方案3】:

如果您想保留下划线以便您的谓词函数更灵活,这里有 2 个想法。

方法一

由于_.find 的谓词同时接收元素的值和索引,您可以使用副作用来检索索引,如下所示:

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

方法二

看下划线源码,_.find是这样实现的:

_.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;
};

要使其成为findIndex 函数,只需将result = value; 行替换为result = index; 这与第一种方法的想法相同。我包含它是为了指出下划线使用副作用来实现_.find

【讨论】:

    【解决方案4】:

    我不知道是否存在执行此操作的现有下划线方法,但您可以使用纯 javascript 实现相同的结果。

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

    那么你可以这样做:

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

    【讨论】:

    • 为什么不默认return -1;
    【解决方案5】:

    如果您的目标环境支持 ES2015(或者您有转译步骤,例如使用 Babel),您可以使用原生 Array.prototype.findIndex()。

    举个例子

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

    【讨论】:

      【解决方案6】:

      你可以使用lodash中的indexOf方法

      var tv = [{id:1},{id:2}]
      var voteID = 2;
      var data = _.find(tv, function(voteItem){ return voteItem.id == voteID; });
      var index=_.indexOf(tv,data);
      

      【讨论】:

        【解决方案7】:

        保持简单:

        // 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
        

        或者,对于非仇恨者,CoffeeScript 变体:

        findIndex = (arr, cond) ->
          for i, x of arr
            return parseInt(i) if cond(x)
        

        【讨论】:

        • 最好是return parseInt(i) for i, x of array when cond(x)
        • 这怎么比以前的答案简单??
        【解决方案8】:

        这是为了帮助lodash 用户。通过执行以下操作检查您的密钥是否存在:

        hideSelectedCompany(yourKey) {
         return _.findIndex(yourArray, n => n === yourKey) === -1;
        }
        

        【讨论】:

          【解决方案9】:

          最简单的解决方案是使用lodash:

          1. 安装 lodash:

          npm install --save lodash

          1. 使用方法findIndex:

          const _ = require('lodash');

          findIndexByElementKeyValue = (elementKeyValue) => {
            return _.findIndex(array, arrayItem => arrayItem.keyelementKeyValue);
          }
          

          【讨论】:

            【解决方案10】:

            如果您期望多个匹配项并因此需要返回一个数组,请尝试:

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

            如果属性值是唯一的并且需要匹配的索引,试试:

            _.findWhere(Users, {_id: 10})
            

            【讨论】:

              【解决方案11】:
              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);
              

              【讨论】:

                【解决方案12】:

                我遇到了类似的情况,但相反是根据给定对象的索引找到使用的键。我可以在 underscore 中找到解决方案,使用 Object.values 将对象返回到数组中以获取发生的索引。

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

                【讨论】:

                  【解决方案13】:

                  如果您想通过 id 从对象中获取特定键值,请使用

                  var tv = [{id:1, name:"ABC"},{id:2, name:xyz}]
                  
                  _.find(tv , {id:1}).value // retrun "ABC"
                  

                  【讨论】:

                    猜你喜欢
                    • 2018-12-05
                    • 1970-01-01
                    • 1970-01-01
                    • 2021-12-12
                    • 2012-05-28
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    相关资源
                    最近更新 更多