53
If you're already using ECMAScript 5 in your code you can use that:
myArray
.map(function (element) {return element.color;})
.indexOf('blue');
Note that the support to these functions is a quite limited (they don't work on Internet Explorer 8).
Also, if you're in the future, and you're using ES6 you can do that:
myArray.map((el) => el.color).indexOf('blue');
That's the same as above, but smaller.
I'm guessing you mean from your example to return "1"? Here is a function for you...
<script type='text/javascript'>
var myArray = [
{
'color':'red',
'name': 'redName'
},
{
'color':'blue',
'name': 'blueName'
},
{
'color':'green',
'name': 'greenName'
},
{
'color':'yellow',
'name': 'yellowName'
},
];
function getIndexOf(a,v) {
var l = a.length;
for (var k=0;k<l;k++) {
if (a[k].color==v) {
return k;
}
}
return false;
}
alert (getIndexOf(myArray,'blue'));
</script>