在下划线中,我可以成功找到具有特定键值的项目
var tv = [{id:1},{id:2}]
var voteID = 2;
var data = _.find(tv, function(voteItem){ return voteItem.id == voteID; });
//data = { id: 2 }
但是如何找到该对象发生的数组索引?
我不知道是否存在执行此操作的现有下划线方法,但您可以使用普通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)]
这是为了帮助lodash
用户。通过以下方式检查您的密钥是否存在:
hideSelectedCompany(yourKey) {
return _.findIndex(yourArray, n => n === yourKey) === -1;
}
最简单的解决方案是使用lodash:
npm install --save lodash
const _ = require('lodash');
findIndexByElementKeyValue = (elementKeyValue) => {
return _.findIndex(array, arrayItem => arrayItem.keyelementKeyValue);
}
findIndex
在1.8中添加:
index = _.findIndex(tv, function(voteItem) { return voteItem.id == voteID })
见:http://underscorejs.org/#findIndex
或者,如果您不介意制作另一个临时列表,这也有效:
index = _.indexOf(_.pluck(tv, 'id'), voteId);
如果你想留下下划线,那么你的谓词函数可以更灵活,这里有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
。
如果您的目标环境支持ES2015(或者您有一个简单的步骤,例如使用Babel),则可以使用本机Array.prototype.findIndex()。
举个例子
const array = [ {id:1}, {id:2} ]
const desiredId = 2;
const index = array.findIndex(obj => obj.id === desiredId);
你可以使用indexOf
的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);
保持简单:
// 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)
如果您期望多个匹配,因此需要返回一个数组,请尝试:
_.where(Users, {age: 24})
如果属性值是唯一的并且您需要匹配的索引,请尝试:
_.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);