Sometimes, we want to find index of an object by key and value in a JavaScript array.
In this article, we’ll look at how to find index of an object by key and value in a JavaScript array.
How to find index of an object by key and value in a JavaScript array?
To find index of an object by key and value in a JavaScript array, we can use the array findIndex method.
For instance, we write
const peoples = [
{ attr1: "bob", attr2: "pizza" },
{ attr1: "john", attr2: "sushi" },
{ attr1: "larry", attr2: "hummus" },
];
const index = peoples.findIndex((p) => p.attr1 == "john");
to call peoples.findIndex to find the index of the object in the peoples array with the attr1 property set to 'john'.
Conclusion
To find index of an object by key and value in a JavaScript array, we can use the array findIndex method.