json index of property value

后端 未结 6 1375
春和景丽
春和景丽 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:00

    Just loop through the list until you find the matching id.

    function indexOf(list, id) {
      for (var i = 0; i < list.length; i++) {
        if (list[i]._id === id) { return i; }
      }
      return -1;
    }
    
    0 讨论(0)
  • 2020-12-18 09:05
    var i = list.length;
    while( i-- ) {
        if( list[i]._id === '4dd80b16e8a6c428a900007d' ) break;
    }
    
    alert(i);  // will be -1 if no match was found
    
    0 讨论(0)
  • 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.
    
    0 讨论(0)
  • 2020-12-18 09:19

    Since there is no index of your data structure by _id, something is going to have to loop over the structure and find an _id value that matches.

    function findId(data, id) {
        for (var i = 0; i < data.length; i++) {
            if (data[i]._id == id) {
                return(data[i]);
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-18 09:20

    You can try Array.prototype.map, based on your example it will be:

    var index = list.map(function(e) { return e._id; }).indexOf('4dd822c5e8a6c42aa70000ad');
    

    Array.prototype.map is not available on IE7 or IE8. ES5 Compatibility

    0 讨论(0)
  • 2020-12-18 09:25
    function index_of(haystack, needle) {
        for (var i = 0, l = haystack.length; i < l; ++i) {
            if( haystack[i]._id === needle ) {
               return i;   
            }
        }
        return -1;
    }
    
    console.log(index_of(list, '4dd80b16e8a6c428a900007d'));
    

    same as the above, but caches the length of the haystack.

    0 讨论(0)
提交回复
热议问题