我怎样才能简单直接地找到满足某些条件的对象数组中的索引?
例如,给定这个输入:
var hello = {
hello: 'world',
foo: 'bar'
};
var qaz = {
hello: 'stevie',
foo: 'baz'
}
var myArray = [];
myArray.push(hello, qaz);
我如何搜索myArray找到其hello属性等于'stevie'的元素的索引(在这种情况下,结果应该是1)?
我怎样才能简单直接地找到满足某些条件的对象数组中的索引?
例如,给定这个输入:
var hello = {
hello: 'world',
foo: 'bar'
};
var qaz = {
hello: 'stevie',
foo: 'baz'
}
var myArray = [];
myArray.push(hello, qaz);
我如何搜索myArray找到其hello属性等于'stevie'的元素的索引(在这种情况下,结果应该是1)?
当前回答
array.filter(function(item, indx, arr){ return(item.hello === 'stevie'); })[0];
小心[0]。
在安东尼奥·拉古纳的回答中使用reduce是恰当的。
抱歉这么简短……
其他回答
这无需自定义代码即可实现
var arr, a, found;
arr = [{x: 1, y: 2}];
a = {x: 1, y: 2};
found = JSON.stringify(arr).indexOf(JSON.stringify(a)) > - 1;
// found === true
注意:这并没有给出实际的索引,它只告诉你的对象是否存在于当前的数据结构中
试试这个:
console.log(Object.keys({foo:"_0_", bar:"_1_"}).indexOf("bar"));
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
如果你只是对这个职位感兴趣,请参阅@Pablo的答案。
pos = myArray.map(function(e) { return e.hello; }).indexOf('stevie');
然而,如果你希望找到元素(例如,如果你正在考虑做这样的myArray[pos]),有一个更有效的单行方法来做,使用过滤器。
element = myArray.filter((e) => e.hello === 'stevie')[0];
参见性能结果(~ +42% ops/sec): http://jsbench.github.io/#7fa01f89a5dc5cc3bee79abfde80cdb3
或者创建原型:
Array.prototype.indexOfObject = function arrayObjectIndexOf(property, value) {
for (var i = 0, len = this.length; i < len; i++) {
if (this[i][property] === value) return i;
}
return -1;
}
myArr.indexOfObject("name", "stevie");
请看这个例子:http://jsfiddle.net/89C54/
for (i = 0; i < myArray.length; i++) {
if (myArray[i].hello === 'stevie') {
alert('position: ' + i);
return;
}
}
它从零开始计数。