Get Index of Object in Array by Property in JavaScript
Table of Contents
When you have an array of objects, finding if an object exists in it is trickier than if the array was of primitives, like strings or numbers.
This is because objects can take many different forms and have different data values in them.
In this post, we'll learn how you find the index of an object in an array by property in JavaScript.
Finding the Index of an Object in an Array by Property
First let's start off with an example object:
JAVASCRIPTconst object = {
name: "John",
age: 30
};
This is an object with two properties, name
and age
. Now imagine you have an array of objects like these:
JAVASCRIPTconst array = [
{
name: "John",
age: 30
},
{
name: "Sally",
age: 40
}
];
To find the object by property, we can use the built-in findindex
method.
This array method is called on the array itself, and you must provide it with a callback function.
This callback function is what determines if the current element in the array is what you're looking for.
If we want to find a person named John
who has the age of 30
, we can provide a function that checks both values:
JAVASCRIPTconst object = {
name: "John",
age: 30
};
const array = [
{
name: "John",
age: 30
},
{
name: "Sally",
age: 40
}
];
const index = array.findIndex((person) => {
return person.name === object.name && person.age === object.age;
});
console.log(index);
BASH0
As expected, we get the value 0
back, which is the index of the first element in the array that matches the criteria.
This function would return -1
if the object wasn't found, which is important to remember.
Using the return value, we can turn the return value into a boolean:
JAVASCRIPTconst exists = array.findIndex((person) => person.name === object.name && person.age === object.age) > -1;
console.log(exists);
Depending on what you pass in as the callback function, you have full control over when the element fits what you're looking for.
Conclusion
In this post, we learned how to find the index of an object in an array by property in JavaScript.
Make use of the powerful findindex
method and pass it a callback function describing your criteria to find the object.
Hopefully, this has been helpful. Thanks for reading!
- Getting Started with Solid
- Getting Started with Express
- Create an RSS Reader in Node
- How to deploy a .NET app using Docker
- How to build a Discord bot using TypeScript
- How to deploy a Node app using Docker
- Getting Started with Sass
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Using Push.js to Display Web Browser Notifications
- Getting Started with React
- Setting Up Stylus CSS Preprocessor
- Getting Started with Vuex: Managing State in Vue