我怎样才能简单直接地找到满足某些条件的对象数组中的索引?

例如,给定这个输入:

var hello = {
    hello: 'world',
    foo: 'bar'
};
var qaz = {
    hello: 'stevie',
    foo: 'baz'
}

var myArray = [];
myArray.push(hello, qaz);

我如何搜索myArray找到其hello属性等于'stevie'的元素的索引(在这种情况下,结果应该是1)?


当前回答

对于@Monika Garg的回答,您可以使用findIndex()(对于不受支持的浏览器,有一个polyfill)。

我看到人们对这个答案投了反对票,我希望他们这么做是因为语法错误,因为在我看来,这是最优雅的方式。

如果数组中的元素满足提供的测试函数,则findIndex()方法返回数组中的索引。否则返回-1。

例如:

Var hello = { 你好:“世界”, 喷火:“酒吧” }; Var qaz = { 你好:史蒂夫, 喷火:“记者” } var myArray = []; myArray.push(你好,qaz); var index = myArray.findIndex(函数(元素){ 返回元素。Hello == 'stevie'; }); 警报(指数);

其他回答

array.filter(function(item, indx, arr){ return(item.hello === 'stevie'); })[0];

小心[0]。

在安东尼奥·拉古纳的回答中使用reduce是恰当的。

抱歉这么简短……

var idx = myArray.reduce( function( cur, val, index ){

    if( val.hello === "stevie" && cur === -1 ) {
        return index;
    }
    return cur;

}, -1 );

我已经做了一个通用函数来检查下面是代码&适用于任何对象

function indexOfExt(list, item) {
    var len = list.length;

    for (var i = 0; i < len; i++) {
        var keys = Object.keys(list[i]);
        var flg = true;
        for (var j = 0; j < keys.length; j++) {
            var value = list[i][keys[j]];
            if (item[keys[j]] !== value) {
                flg = false;
            }
        }
        if (flg == true) {
            return i;
        }
    }
    return -1;
}

var items = [{ "hello": 'world', "foo": 'bar' }];
var selectedItem = { "hello": 'world', "foo": 'bar' };
alert(items.indexOf(selectedItem));
alert(indexOfExt(items, selectedItem));

第一个警报将返回-1(表示未找到匹配),第二个警报将返回0(表示找到匹配)。

你可以简单地使用

const someId = 2; Const数组= [{id:1}, {id:2}, {id:3}]; 常量索引=数组。Reduce ((i, item, index) => item。id === someId ?索引:i, -1); alert('someId ' + someId + ' is at index ' + index);

没有下划线,没有for,只有一个略读。

使用_。从underscore.js库中找到findIndex

下面是例子 _。findIndex ([{: 1}, {2, c: 10}, {: 3}), {: 2, c: 10}) / / 1