To get the index of an object by its property in JavaScript, we use the map
and indexOf
methods.
For instance, we write
const data = [
{ id: 1, name: "Nick", token: "312312" },
{ id: 2, name: "John", token: "123123" },
];
const index = data.map((e) => e.name).indexOf("Nick");
to call data.map
with a callback to return an array with the name
property of each object.
And then we call indexOf
to get the index of the entry with 'Nick'
in the returned array.