indexOf method in an object array?

前端 未结 27 2478
别跟我提以往
别跟我提以往 2020-11-22 02:18

What\'s the best method to get the index of an array which contains objects?

Imagine this scenario:

var hello = {
    hello: \'world\',
    foo: \'ba         


        
27条回答
  •  醉酒成梦
    2020-11-22 02:44

    If you are only interested into finding the position see @Pablo's answer.

    pos = myArray.map(function(e) { return e.hello; }).indexOf('stevie');

    However, if you are looking forward to finding the element (i.e. if you were thinking of doing something like this myArray[pos]), there is a more efficient one-line way to do it, using filter.

    element = myArray.filter((e) => e.hello === 'stevie')[0];

    See perfomance results (~ +42% ops/sec): http://jsbench.github.io/#7fa01f89a5dc5cc3bee79abfde80cdb3

提交回复
热议问题