How to get index of object by its property in JavaScript?

rsboarder picture rsboarder · Aug 24, 2011 · Viewed 299.1k times · Source

For example, I have:

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

Then, I want to sort/reverse this object by name, for example. And then I want to get something like this:

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

And now I want to know the index of the object with property name='John' to get the value of the property token.

How do I solve the problem?

Answer

German Attanasio picture German Attanasio · Apr 4, 2014

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

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

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