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!
- How to Install Node on Windows, macOS and Linux
- Getting Started with Solid
- Managing PHP Dependencies with Composer
- Getting Started with Electron
- How to build a Discord bot using TypeScript
- How to deploy a Deno app using Docker
- Learn how to use v-model with a custom Vue component
- How to Scrape the Web using Node.js and Puppeteer
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Learn how to build a Slack Bot using Node.js
- Creating a Twitter bot with Node.js
- Using Push.js to Display Web Browser Notifications