Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 908
rsboarder Avatar asked Aug 24 '11 14:08

rsboarder


People also ask

How do you find the index of an object property?

To get a value of an object by index, call the Object. values() method to get an array of the object's values and use bracket notation to access the value at the specific index, e.g. Object. values(obj)[1] . Copied!

How do you find the index of an object in an object?

To find the index of an object in an array, by a specific property: Use the map() method to iterate over the array, returning only the value of the relevant property. Call the indexOf() method on the returned from map array. The indexOf method returns the index of the first occurrence of a value in an array.


11 Answers

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'); 

var Data = [{     id_list: 1,     name: 'Nick',     token: '312312'   },   {     id_list: 2,     name: 'John',     token: '123123'   } ] var index = Data.map(function(e) {   return e.name; }).indexOf('Nick'); console.log(index)

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'); 
like image 159
German Attanasio Avatar answered Sep 24 '22 04:09

German Attanasio


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');
like image 26
silverlight513 Avatar answered Sep 24 '22 04:09

silverlight513


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().

like image 32
Chris Pickett Avatar answered Sep 21 '22 04:09

Chris Pickett


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");
like image 44
Alain T. Avatar answered Sep 23 '22 04:09

Alain T.


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.

like image 33
edank Avatar answered Sep 23 '22 04:09

edank


Only way known to me is to loop through all array:

var index = -1;
for(var i=0; i<Data.length; i++)
  if(Data[i].name === "John") {
    index = i;
    break;
  }

Or case insensitive:

var index = -1;
for(var i=0; i<Data.length; i++)
  if(Data[i].name.toLowerCase() === "john") {
    index = i;
    break;
  }

On result variable index contain index of object or -1 if not found.

like image 33
Andrew D. Avatar answered Sep 23 '22 04:09

Andrew D.


A prototypical way

(function(){
  if (!Array.prototype.indexOfPropertyValue){
       Array.prototype.indexOfPropertyValue = function(prop, value){
      for (var index = 0; index < this.length; index++){
        if (this[index][prop]){
          if (this[index][prop] == value){
            return index;
          }
        }
       }
      return -1;
    }
  }
 })();

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

 Data.indexOfPropertyValue('name', 'John'); // Returns 1 (index of array);
 Data.indexOfPropertyValue('name', 'Invalid name') // Returns -1 (no result);
 var indexOfArray = Data.indexOfPropertyValue('name', 'John');
 Data[indexOfArray] // Returns the desired object.
like image 30
Patrik Wallin Avatar answered Sep 24 '22 04:09

Patrik Wallin


you can use filter method

 const filteredData = data.filter(e => e.name !== 'john');
like image 41
Sakhri Houssem Avatar answered Sep 22 '22 04:09

Sakhri Houssem


Just go through your array and find the position:

var i = 0;
for(var item in Data) {
    if(Data[item].name == 'John')
        break;
    i++;
}
alert(i);
like image 29
Sascha Galley Avatar answered Sep 23 '22 04:09

Sascha Galley


let indexOf = -1;
let theProperty = "value"
let searchFor = "something";

theArray.every(function (element, index) {

    if (element[theProperty] === searchFor) {
        indexOf = index;
        return false;
    }
    return true;
});
like image 25
Itay Merchav Avatar answered Sep 20 '22 04:09

Itay Merchav


collection.findIndex(item => item.value === 'smth') !== -1
like image 20
Eugene Lyzo Avatar answered Sep 22 '22 04:09

Eugene Lyzo