indexOf method in an object array?

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

    In ES2015, this is pretty easy:

    myArray.map(x => x.hello).indexOf('stevie')
    

    or, probably with better performance for larger arrays:

    myArray.findIndex(x => x.hello === 'stevie')
    
    0 讨论(0)
  • 2020-11-22 02:28

    Or prototype it :

    Array.prototype.indexOfObject = function arrayObjectIndexOf(property, value) {
        for (var i = 0, len = this.length; i < len; i++) {
            if (this[i][property] === value) return i;
        }
        return -1;
    }
    
    myArr.indexOfObject("name", "stevie");
    
    0 讨论(0)
  • 2020-11-22 02:29

    Try this:

    console.log(Object.keys({foo:"_0_", bar:"_1_"}).indexOf("bar"));
    

    https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/keys

    0 讨论(0)
  • 2020-11-22 02:29

    simple:

    myArray.indexOf(myArray.filter(function(item) {
        return item.hello == "stevie"
    })[0])
    
    0 讨论(0)
  • 2020-11-22 02:29

    You can simply use

    const someId = 2;
    const array = [{id:1}, {id:2}, {id:3}];
    const index = array.reduce((i, item, index) => item.id === someId ? index : i, -1);
    alert('someId ' + someId + ' is at index ' + index);

    No underscore, no for, just a reduce.

    0 讨论(0)
  • 2020-11-22 02:30

    Brief

    myArray.indexOf('stevie','hello')
    

    Use Cases :

      /*****NORMAL****/  
    [2,4,5].indexOf(4) ;//OUTPUT 1
     /****COMPLEX*****/
     [{slm:2},{slm:4},{slm:5}].indexOf(4,'slm');//OUTPUT 1
     //OR
     [{slm:2},{slm:4},{slm:5}].indexOf(4,function(e,i){
       return e.slm;
    });//OUTPUT 1
    /***MORE Complex**/
    [{slm:{salat:2}},{slm:{salat:4}},{slm:{salat:5}}].indexOf(4,function(e,i){
       return e.slm.salat;
    });//OUTPUT 1
    

    API :

        Array.prototype.indexOfOld=Array.prototype.indexOf
    
        Array.prototype.indexOf=function(e,fn){
          if(!fn){return this.indexOfOld(e)}
          else{ 
           if(typeof fn ==='string'){var att=fn;fn=function(e){return e[att];}}
            return this.map(fn).indexOfOld(e);
          }
        };
    
    0 讨论(0)
提交回复
热议问题