得到的数组内的对象的索引,匹配的条件 [英] Get the index of the object inside an array, matching a condition

查看:118
本文介绍了得到的数组内的对象的索引,匹配的条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的数组:

[{prop1:"abc",prop2:"qwe"},{prop1:"bnmb",prop2:"yutu"},{prop1:"zxvz",prop2:"qwrq"},...]

我怎样才能获得对象塔比赛的一个条件指数(不沿阵列迭代)?

How can I get the index of the object tha match a condition (without iterate along the array)?

例如:为 prop2 ==玉兔,我想获得指数 1

For instance: for the prop2=="yutu", I want to get index 1.

我看到了 .indexOf()方法,但认为它是用于简单数组,如: [A1,A2,... ]
我还检查了 $。gr​​ep的()但这返回我的对象​​,而不是指数...

I saw the .indexOf() method but think it's used for simple arrays like: ["a1","a2",...] I checked also the $.grep() but this returns me objects, not the index...

推荐答案

由于人们不断upvoting这一点,这里有一个更新。

Since people keep upvoting this, here's an update.

截至2016年,你应该使用<一个href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex\"><$c$c>Array.findIndex为此:

As of 2016, you're supposed to use Array.findIndex for this:

a = [{prop1:"abc",prop2:"qwe"},{prop1:"bnmb",prop2:"yutu"},{prop1:"zxvz",prop2:"qwrq"}]
index = a.findIndex(x => x.prop2=="yutu")

它在GC,FF和边缘,为MSIEs有链接的页面上的填充工具的支持。

It's supported in GC, FF and Edge, for MSIEs there's a polyfill on the linked page.

使用jQuery:

indexes = $.map(list, function(obj, index) {
    if(obj.prop2 == "yutu") {
        return index;
    }
})

firstIndex = indexes[0]

如果没有jQuery的,稍微复杂一些:

Without jQuery, slightly more complicated:

indexes = list.map(function(obj, index) {
    if(obj.prop2 == "yutu") {
        return index;
    }
}).filter(isFinite)

这篇关于得到的数组内的对象的索引,匹配的条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆