arrays - How can I get the index of an object by its property in JavaScript?

ID : 10195

viewed : 24

Tags : javascriptarraysobjectjavascript

Top 5 Answer for arrays - How can I get the index of an object by its property in JavaScript?

vote vote

95

Since the sort part is already answered. I'm just going to propose another elegant way to get the indexOf of a property in your array

Your example is:

var Data = [     {id_list:1, name:'Nick', token:'312312'},     {id_list:2, name:'John', token:'123123'} ] 

You can do:

var index = Data.map(function(e) { return e.name; }).indexOf('Nick'); 

Array.prototype.map is not available on Internet Explorer 7 or Internet Explorer 8. ES5 Compatibility

And here it is with ES6 and arrow syntax, which is even simpler:

const index = Data.map(e => e.name).indexOf('Nick'); 
vote vote

84

If you're fine with using ES6, arrays now have the findIndex function. Which means you can do something like this:

const index = Data.findIndex(item => item.name === 'John'); 
vote vote

71

As the other answers suggest, looping through the array is probably the best way. But I would put it in its own function, and make it a little more abstract:

function findWithAttr(array, attr, value) {     for(var i = 0; i < array.length; i += 1) {         if(array[i][attr] === value) {             return i;         }     }     return -1; }  var Data = [     {id_list: 2, name: 'John', token: '123123'},     {id_list: 1, name: 'Nick', token: '312312'} ]; 

With this, not only can you find which one contains 'John', but you can find which contains the token '312312':

findWithAttr(Data, 'name', 'John'); // returns 0 findWithAttr(Data, 'token', '312312'); // returns 1 findWithAttr(Data, 'id_list', '10'); // returns -1 

The function returns -1 when not found, so it follows the same construct as Array.prototype.indexOf().

vote vote

61

If you're having issues with Internet Explorer, you could use the map() function which is supported from 9.0 onward:

var index = Data.map(item => item.name).indexOf("Nick"); 
vote vote

50

var index = Data.findIndex(item => item.name == "John") 

Which is a simplified version of:

var index = Data.findIndex(function(item){ return item.name == "John"}) 

From mozilla.org:

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.

Top 3 video Explaining arrays - How can I get the index of an object by its property in JavaScript?

Related QUESTION?