To find the index of an object by key and value in a JavaScript array, we can use the JavaScript array’s findIndex
method.
For instance, we can write:
const peoples = [{
"attr1": "bob",
"attr2": "pizza"
},
{
"attr1": "john",
"attr2": "sushi"
},
{
"attr1": "larry",
"attr2": "hummus"
}
];
const index = peoples.findIndex((person) => {
return person.attr1 === "john"
});
console.log(index)
We create the peoples
array with objects that have the attr1
and attr2
properties.
Then we call findIndex
on peoples
with a callback that returns person.attr1 === 'john'
.
This will return the index of the first object that has the attr1
property value set to 'john'
.
Therefore, index
is 1 as a result.