indexOf method in an object array?

前端 未结 27 3108
别跟我提以往
别跟我提以往 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:35

    Furthor of @Monika Garg answer, you can use findIndex() (There is a polyfill for unsupprted browsers).

    I saw that people downvoted this answer, and I hope that they did this because of the wrong syntax, because on my opinion, this is the most elegant way.

    The findIndex() method returns an index in the array, if an element in the array satisfies the provided testing function. Otherwise -1 is returned.

    For example:

    var hello = {
      hello: 'world',
      foo: 'bar'
    };
    var qaz = {
      hello: 'stevie',
      foo: 'baz'
    }
    
    var myArray = [];
    myArray.push(hello,qaz);
    
    var index = myArray.findIndex(function(element) {
      return element.hello == 'stevie';
    });
    
    alert(index);

提交回复
热议问题