redconservatory redconservatory - 4 months ago 16
Javascript Question

Javascript indexOf on an array of objects

if I have an array like:

var myArray = [
{
'color':'red',
'name': 'redName'
},
{
'color':'blue',
'name': 'blueName'
},
{
'color':'green',
'name': 'greenName'
},
{
'color':'yellow',
'name': 'yellowName'
},
];


How do I get the index of say, "blue"?

Answer
for(var i = 0; i < myArray.length; i++) {
   if(myArray[i].color === 'blue') {
     return i;
   }
}

There's no "clean" way unless you want to involve a third-party library. Underscore is a good one for stuff like this.

Comments