简体   繁体   English

在下划线中找到具有特定键值的 object 的数组索引

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

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){ return voteItem.id == voteID; });
//data = { id: 2 }

but how do I find what array index that object occurred at?但是我如何找到 object 出现的数组索引?

findIndex was added in 1.8: findIndex在1.8中添加:

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

See: http://underscorejs.org/#findIndex 请参阅: 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 见: http//underscorejs.org/#pluck

If you want to stay with underscore so your predicate function can be more flexible, here are 2 ideas. 如果你想留下下划线,那么你的谓词函数可以更灵活,这里有2个想法。

Method 1 方法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: 由于_.find的谓词_.find接收元素的值和索引,因此可以使用副作用来检索索引,如下所示:

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

Method 2 方法2

Looking at underscore source, this is how _.find is implemented: 查看下划线源代码,这是_.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;
};

To make this a findIndex function, simply replace the line result = value; 要使其成为findIndex函数,只需替换行result = value; with result = index; 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. 我把它包括在内,指出下划线使用副作用来实现_.find

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

In your case, I would do: 在你的情况下,我会这样做:

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

Give it a try. 试试看。

I don't know if there is an existing underscore method that does this, but you can achieve the same result with plain javascript. 我不知道是否存在执行此操作的现有下划线方法,但您可以使用普通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)]

If your target environment supports ES2015 (or you have a transpile step, eg with Babel), you can use the native Array.prototype.findIndex(). 如果您的目标环境支持ES2015(或者您有一个简单的步骤,例如使用Babel),则可以使用本机Array.prototype.findIndex()。

Given your example 举个例子

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

you can use indexOf method from lodash 你可以使用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);

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: 或者,对于非仇恨者,CoffeeScript变体:

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

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})
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);

This is to help lodash users. 这是为了帮助lodash用户。 check if your key is present by doing: 通过以下方式检查您的密钥是否存在:

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

The simplest solution is to use lodash: 最简单的解决方案是使用lodash:

  1. Install lodash: 安装lodash:

npm install --save lodash npm install --save lodash

  1. Use method findIndex: 使用方法findIndex:

const _ = require('lodash'); const _ = require('lodash');

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

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.我可以在下划线中找到解决方案,使用Object.values将 object 返回到数组中以获取发生的索引。

 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>

And If you want some particular key value from an object by id then use如果你想通过 id 从 object 中获得一些特定的键值,那么使用

var tv = [{id:1, name:"ABC"},{id:2, name:xyz}]

_.find(tv , {id:1}).value // retrun "ABC"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM