我怎样才能简单直接地找到满足某些条件的对象数组中的索引?
例如,给定这个输入:
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)?
当前回答
然而,大多数其他答案都是有效的。有时候,最好在你要使用它的地方创建一个简短的函数。
// indexOf wrapper for the list of objects
function indexOfbyKey(obj_list, key, value) {
for (index in obj_list) {
if (obj_list[index][key] === value) return index;
}
return -1;
}
// Find the string in the list (default -1)
var test1 = indexOfbyKey(object_list, 'name', 'Stevie');
var test2 = indexOfbyKey(object_list, 'last_name', 'some other name');
这取决于什么对你来说是重要的。使用一行代码可能会节省代码行数,或者将一个通用的解决方案放在覆盖各种边缘情况的某个地方是非常聪明的。但有时最好直接说:“这里我是这样做的”,而不是让未来的开发人员做额外的逆向工程工作。特别是如果你认为自己是“新手”,就像你的问题一样。
其他回答
请看这个例子:http://jsfiddle.net/89C54/
for (i = 0; i < myArray.length; i++) {
if (myArray[i].hello === 'stevie') {
alert('position: ' + i);
return;
}
}
它从零开始计数。
array.filter(function(item, indx, arr){ return(item.hello === 'stevie'); })[0];
小心[0]。
在安东尼奥·拉古纳的回答中使用reduce是恰当的。
抱歉这么简短……
这是在数组中查找对象索引的方法
var myArray = [{ hello: 'world',
foo: 'bar'
},{
hello: 'stevie',
foo: 'baz'
}];
for (i = 0; i < myArray.length; i++) {
if (myArray[i].hello === 'stevie') {
alert('position: ' + i);
return;
}
}
你可以使用一个本地方便的函数Array.prototype.findIndex():
如果数组中的元素满足提供的测试函数,则findIndex()方法返回数组中的索引。否则返回-1。
只是需要注意的是,它不支持Internet Explorer, Opera和Safari,但你可以使用下面链接提供的Polyfill。
更多信息:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex
Var hello = { 你好:“世界”, 喷火:“酒吧” }; Var qaz = { 你好:史蒂夫, 喷火:“记者” } var myArray = []; myArray。推动(你好,qaz); var index = myArray。findIndex(函数(元素,索引,数组){ 如果元素。你好=== 'stevie') { 返回true; } }); Alert ('stevie is at index: ' + index);
我更喜欢使用findIndex()方法:
var index = myArray.findIndex('hello','stevie');
Index会给出索引号。