Json index property values

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

here is a sample code

var list = [ { _id: '4dd822c5e8a6c42aa70000ad', metadata: { album: 'American IV: Man Comes Around', song: 'Hurt', coverart: 'http://images.mndigital.com/albums/044/585/435/m.jpeg', artist: 'Johnny Cash', length: 216, mnid: '44585439' } }, { _id: '4dd80b16e8a6c428a900007d', metadata: { album: 'OK Computer (Collector\ Edition)', song: 'Paranoid Android', coverart: 'http://images.mndigital.com/albums/026/832/735/m.jpeg', artist: 'Radiohead', length: 383, mnid: '26832739' } }, { _id: '4dd68694e8a6c42c80000479', metadata: { album: 'The Presidents Of The United States Of America: Ten Year Super Bonus Special Anniversary Edition', song: 'Lump', coverart: 'http://images.mndigital.com/albums/011/698/433/m.jpeg', artist: 'The Presidents Of The United States Of America', length: 134, mnid: '11698479' } } ] 

then pseudo code

  var index_of = list.indexOf("4dd80b16e8a6c428a900007d"); 

obviously this will not work, but I am wondering if there is anyway to do this without a loop to find the index?

+4
source share
6 answers
 var i = list.length; while( i-- ) { if( list[i]._id === '4dd80b16e8a6c428a900007d' ) break; } alert(i); // will be -1 if no match was found 
+10
source

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 not available in IE7 or IE8. ES5 Compatibility

+5
source

Since the _id index _id not contain the index of your data structure, you will need to sort through the structure and find the _id value that matches.

 function findId(data, id) { for (var i = 0; i < data.length; i++) { if (data[i]._id == id) { return(data[i]); } } } 
+1
source

Just scroll through the list until you find the corresponding identifier.

 function indexOf(list, id) { for (var i = 0; i < list.length; i++) { if (list[i]._id === id) { return i; } } return -1; } 
+1
source
 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')); 

as above but caches the length of the haystack.

+1
source

prototype method

 (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. 
+1
source

Source: https://habr.com/ru/post/1387314/


All Articles