简体   繁体   English

在JavaScript中的对象数组中查找数组元素的索引?

[英]Finding the index of an array element in an array of objects in JavaScript?

(First off, I've been reading questions and answers here for a long time but this is my first post.) (首先,我已经在这里阅读问题和答案很长时间了,但这是我的第一篇文章。)

I've found solutions that involve writing your own function for it, but I have to believe there's a built-in way to do this. 我已经找到了涉及为此编写自己的函数的解决方案,但是我必须相信有一种内置的方法可以做到这一点。

I'm working in JavaScript and have an array of custom objects, each of which look like this: 我正在使用JavaScript,并且有一个自定义对象数组,每个对象如下所示:

{ prop1: "1", prop2: "blah", prop3: "news", prop4: "2", prop5: "1" }
{ prop1: "2", prop2: "foo", prop3: "news", prop4: "2", prop5: "1" }
{ prop1: "3", prop2: "bar", prop3: "news", prop4: "2", prop5: "1" }
{ prop1: "4", prop2: "hello", prop3: "news", prop4: "2", prop5: "1" }

I want to find a built-in way to find the array index of one of the objects given the value of one of its properties (for this example, if I gave it "prop2" and "bar" it would return index 2). 我想找到一种内置方法来找到给定对象之一属性值的对象的数组索引(对于本例,如果我给它“ prop2”和“ bar”,它将返回索引2)。 It would be nice to use .indexOf like you'd expect, but apparently with an array of custom objects, it doesn't work that way. 像您期望的那样使用.indexOf会很好,但是显然对于自定义对象数组,它不能那样工作。

I've found code for a function of my own that works fine, but in my stubbornness I'm convinced there's just got to be a built-in way to do it. 我已经找到了可以正常工作的功能代码,但是我很固执,我坚信必须有一种内置的方式来实现它。 I'm doing a ton of stuff in jQuery in this project, so that's absolutely an option as well. 在这个项目中,我正在用jQuery做大量工作,因此这绝对也是一种选择。 Any suggestions? 有什么建议么?

You can extend the native array prototype to do this, with both property and value as strings. 您可以使用propertyvalue作为字符串来扩展本机数组原型来执行此操作。 Here is a JSFiddle to demonstrate that 这是一个JSFiddle来证明

Array.prototype.indexOfAssociative=function(property,value){
    for(var i=0;i<this.length;i++){
          if(this[i][property]==value){
               return i;
          }

    }
    return -1;
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM