查找具有下划线中特定键值的对象的数组索引

问题描述 投票:82回答:11

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

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
11个回答
28
投票

我不知道是否存在执行此操作的现有下划线方法,但您可以使用普通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)]


0
投票

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

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

0
投票

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

  1. 安装lodash:

npm install --save lodash

  1. 使用方法findIndex:

const _ = require('lodash');

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

162
投票

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


37
投票

如果你想留下下划线,那么你的谓词函数可以更灵活,这里有2个想法。

Method 1

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

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

Method 2

查看下划线源代码,这就是_.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


33
投票

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

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

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

试试看。


10
投票

如果您的目标环境支持ES2015(或者您有一个简单的步骤,例如使用Babel),则可以使用本机Array.prototype.findIndex()。

举个例子

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

4
投票

你可以使用indexOflodash方法

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

3
投票

保持简单:

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

0
投票

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

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

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

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

0
投票
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);
© www.soinside.com 2019 - 2024. All rights reserved.