Use the findIndex() method, by passing a provided callback function as an argument to find an index of the object in the array by property value in JavaScript.
This means you can do something like this:
data.findIndex(item => item.name === 'John');
//OR
arr.findIndex(elem => elem["type"] == 'Invert');
JavaScript finds an index of the object in the array by property value
Simple example code. The function we passed to the Array.findIndex method gets called with each element in the array until it returns a truthy value or iterates over all elements in the array.
<!DOCTYPE html>
<html>
<body>
<script>
const arr = [{id: 'a'}, {id: 'b'}, {id: 'c'}];
const index = arr.findIndex(object => {
return object.id === 'b';
});
console.log(index);
</script>
</body>
</html>
Output:
More Example
<script>
var arr = [
{
"type": "Grayscale",
"mode": "average"
}, {
"type": "Sepia"
}, {
"type": "Invert",
"invert": true
}, {
"type": "Convolute",
"opaque": false,
"matrix": [1, 1, 1, 1, 0.7, -1, -1, -1, -1]
}, {
"type": "Brownie"
}, {
"type": "Brightness",
"brightness": 0.35
}];
var res = arr.findIndex(elem => elem["type"] == 'Invert');
console.log(res);
</script>
Output: 2
Comment if you have any doubts or suggestions on this Js object index topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version