- Published on
TypeScript: How to Find an object in an Array
In TypeScript, you can use the Array.find() method to find an object in an array that matches a given condition. This method returns the first element in the array that satisfies the condition or undefined if no such element is found.
Here's an example that demonstrates how to use the find() method to find a member object in an array of members based on the subscriptionID property:
Example:
interface Member {
fullName: string
subscriptionID: number
}
const members: Member[] = [
{ fullName: 'Mike Smith', subscriptionID: 123 },
{ fullName: 'Johnny Johnson', subscriptionID: 456 },
{ fullName: 'Alex Brown', subscriptionID: 789 },
]
const findMemberByID = (id: number): Member | undefined => {
return members.find((member) => member.subscriptionID === id)
}
const member1 = findMemberByID(123) // Returns { fullName: 'Mike Smith', subscriptionID: 123 }
const member2 = findMemberByID(456) // Returns { fullName: 'Johnny Johnson', subscriptionID: 456 }
const member3 = findMemberByID(999) // Returns undefined
Here, we define an interface Member
that has two properties: fullName
and subscriptionID
. We also define an array members that contains some member objects.
We define a function findMemberByID
that takes an id parameter and returns the member object that has a matching subscriptionID
property. We use the find()
method to search for the member in the members array that matches the given id. If a match is found, the find() method returns the matching object. If no match is found, the find() method returns undefined
.
We call the findMemberByID
function with some example id values and log the results to the console. In the first two cases, the function returns the corresponding member object, and in the third case, the function returns undefined because there is no member object with a subscriptionID of 999 in the members array.
You can modify the condition in the find() method to match any other property or combination of properties in the array objects. The find() method will return the first matching object or undefined if no matching object is found.
Overall, the find()
method is a useful tool for finding objects in arrays in TypeScript. It allows you to easily search for and retrieve objects based on specific conditions, making it an essential method to have in your toolkit.