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"?
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.
In this article, we will learn about the indexOf() method in an Object array in Javascript. To access the index of the object from the array having a value of an object, We are going to use a few of the methods. We will understand both methods through the examples.
The findIndex() method executes a function for each array element. The findIndex() method returns the index (position) of the first element that passes a test. The findIndex() method returns -1 if no match is found. The findIndex() method does not execute the function for empty array elements.
IndexOf(Array, Object, Int32) Searches for the specified object in a range of elements of a one-dimensional array, and returns the index of its first occurrence. The range extends from a specified index to the end of the array.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With