如何通过 JavaScript 中的属性获取对象的索引?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7176908/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 01:12:04  来源:igfitidea点击:

How to get index of object by its property in JavaScript?

javascriptarraysobject

提问by rsboarder

For example, I have:

例如,我有:

var Data = [
  { id_list: 1, name: 'Nick', token: '312312' },
  { id_list: 2, name: 'John', token: '123123' },
]

Then, I want to sort/reversethis object by name, for example. And then I want to get something like this:

然后,例如,我想通过这个对象进行排序/反转name。然后我想得到这样的东西:

var Data = [
  { id_list: 2, name: 'John', token: '123123' },
  { id_list: 1, name: 'Nick', token: '312312' },
]

And now I want to know the index of the object with property name='John'to get the value of the property token.

现在我想知道具有属性的对象的索引name='John'以获取属性令牌的值。

How do I solve the problem?

我该如何解决问题?

采纳答案by Chris Pickett

As the other answers suggest, looping through the array is probably the best way. But I would put it in it's own function, and make it a little more abstract:

正如其他答案所暗示的那样,遍历数组可能是最好的方法。但我会把它放在它自己的函数中,并使它更抽象一点:

function findWithAttr(array, attr, value) {
    for(var i = 0; i < array.length; i += 1) {
        if(array[i][attr] === value) {
            return i;
        }
    }
    return -1;
}

var Data = [
    {id_list: 2, name: 'John', token: '123123'},
    {id_list: 1, name: 'Nick', token: '312312'}
];

With this, not only can you find which one contains 'John' but you can find which contains the token '312312':

有了这个,您不仅可以找到包含“John”的内容,还可以找到包含标记“312312”的内容:

findWithAttr(Data, 'name', 'John'); // returns 0
findWithAttr(Data, 'token', '312312'); // returns 1
findWithAttr(Data, 'id_list', '10'); // returns -1

EDIT:Updated function to return -1 when not found so it follows the same construct as Array.prototype.indexOf()

编辑:更新函数以在未找到时返回 -1,因此它遵循与Array.prototype.indexOf()相同的构造

回答by German Attanasio

Since the sort part is already answered. I'm just going to propose another elegant way to get the indexOf of a property in your array

由于排序部分已经回答。我只是要提出另一种优雅的方法来获取数组中属性的 indexOf

Your example is:

你的例子是:

var Data = [
    {id_list:1, name:'Nick',token:'312312'},
    {id_list:2,name:'John',token:'123123'}
]

You can do:

你可以做:

var index = Data.map(function(e) { return e.name; }).indexOf('Nick');

Array.prototype.mapis not available on IE7 or IE8. ES5 Compatibility

Array.prototype.map在 IE7 或 IE8 上不可用。ES5 兼容性

And here it is with ES6 and arrow syntax, which is even simpler:

这里是 ES6 和箭头语法,更简单:

const index = Data.map(e => e.name).indexOf('Nick');

回答by silverlight513

If you're fine with using ES6. Arrays now have the findIndexfunction. Which means you can do something like this:

如果您可以使用 ES6。数组现在具有findIndex函数。这意味着您可以执行以下操作:

const index = Data.findIndex(item => item.name === 'John');

回答by edank

var index = Data.findIndex(item => item.name == "John")

Which is a simplified version of:

这是以下的简化版本:

var index = Data.findIndex(function(item){ return item.name == "John"})

From mozilla.org:

来自mozilla.org:

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.

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

回答by Alain T.

If you're having issues with IE, you could use the map() function which is supported from 9.0 onward:

如果您在使用 IE 时遇到问题,您可以使用 9.0 以后支持的 map() 函数:

var index = Data.map(item => item.name).indexOf("Nick");

回答by Andrew D.

Only way known for me is to looping through all array:

我知道的唯一方法是循环遍历所有数组:

var index=-1;
for(var i=0;i<Data.length;i++)
  if(Data[i].name==="John"){index=i;break;}

or case insensitive:

或不区分大小写:

var index=-1;
for(var i=0;i<Data.length;i++)
  if(Data[i].name.toLowerCase()==="john"){index=i;break;}

On result variable indexcontain index of object or -1 if not found.

结果变量索引包含对象的索引,如果未找到,则为 -1。

回答by Patrik Wallin

a prototypical way

一种典型的方式

(function(){
  if (!Array.prototype.indexOfPropertyValue){
    Array.prototype.indexOfPropertyValue = function(prop,value){
      for (var index = 0; index < this.length; index++){
        if (this[index][prop]){
          if (this[index][prop] == value){
            return index;
          }
        }
      }
      return -1;
    }
  }
 })();
 // usage:
 var Data = [
 {id_list:1, name:'Nick',token:'312312'},{id_list:2,name:'John',token:'123123'}];
 Data.indexOfPropertyValue('name','John'); // returns 1 (index of array);
 Data.indexOfPropertyValue('name','Invalid name') // returns -1 (no result);
 var indexOfArray = Data.indexOfPropertyValue('name','John');
 Data[indexOfArray] // returns desired object.

回答by Patrik Wallin

Why don't you use a small work-around?

你为什么不使用一个小的解决方法?

Create a new array with names as indexes. after that all searches will use indexes. So, only one loop. After that you don't need to loop through all elements!

创建一个以名称为索引的新数组。之后所有搜索都将使用索引。所以,只有一个循环。之后你不需要遍历所有元素!

var Data = [
    {id_list:1, name:'Nick',token:'312312'},{id_list:2,name:'John',token:'123123'}
    ]
var searchArr = []
Data.forEach(function(one){
  searchArr[one.name]=one;
})
console.log(searchArr['Nick'])

http://jsbin.com/xibala/1/edit

http://jsbin.com/xibala/1/edit

live example.

活生生的例子。

回答by Ed Shee

Extended Chris Pickett's answer because in my case I needed to search deeper than one attribute level:

扩展了 Chris Pickett 的答案,因为在我的情况下,我需要搜索比一个属性级别更深的内容:

function findWithAttr(array, attr, value) {
  if (attr.indexOf('.') >= 0) {
    var split = attr.split('.');
    var attr1 = split[0];
    var attr2 = split[1];
    for(var i = 0; i < array.length; i += 1) {
      if(array[i][attr1][attr2] === value) {
        return i;
      }
    }
  } else {
    for(var i = 0; i < array.length; i += 1) {
      if(array[i][attr] === value) {
        return i;
      }
    }
  };
};

You can pass 'attr1.attr2' into the function

您可以将 'attr1.attr2' 传递给函数

回答by Ed Shee

You can use Array.sort using a custom function as parameter to define your sorting mecanism.

您可以使用 Array.sort 使用自定义函数作为参数来定义您的排序机制。

In your example, it would give :

在你的例子中,它会给出:

var Data = [
    {id_list:1, name:'Nick',token:'312312'},{id_list:2,name:'John',token:'123123'}
]

Data.sort(function(a, b){
    return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
});

alert("First name is : " + Data[0].name); // alerts 'John'
alert("Second name is : " + Data[1].name); // alerts 'Nick'

The sort function must return either -1 if a should come before b, 1 if a should come after b and 0 if both are equal. It's up to you to define the right logic in your sorting function to sort the array.

如果 a 应该在 b 之前,则排序函数必须返回 -1,如果 a 应该在 b 之后,则返回 1,如果两者相等,则返回 0。您可以在排序函数中定义正确的逻辑来对数组进行排序。

Edit : Missed the last part of your question where you want to know the index. You would have to loop through the array to find that as others have said.

编辑:错过了您想知道索引的问题的最后一部分。您必须遍历数组才能找到其他人所说的那样。