json index of property value

后端 未结 6 1383
春和景丽
春和景丽 2020-12-18 08:27

I need to get the index of the json object in an array whose by the objects id

here is the example code

var list = [ { _id: \'4dd822c5e8a6c42aa7000         


        
6条回答
  •  不知归路
    2020-12-18 09:10

    a prototypical way

    (function(){
      if (!Array.prototype.indexOfPropertyValue){
        Array.prototype.indexOfPropertyValue = function(prop,value){
          for (var index = 0; index < this.length; index++){
            if (prop in this[index]){
              if (this[index][prop] == value){
                return index;
              }
            }
          }
          return -1;
        }
      }
     })();
     // usage:
    
     list.indexOfPropertyValue('_id','4dd80b16e8a6c428a900007d'); // returns 1 (index of array);
     list.indexOfPropertyValue('_id','Invalid id') // returns -1 (no result);
     var indexOfArray = list.indexOfPropertyValue('_id','4dd80b16e8a6c428a900007d');
     list[indexOfArray] // returns desired object.
    

提交回复
热议问题