To filter an array of objects in TypeScript and return just one object instead of an array with a single object, you can use the .find()
method instead of the .filter()
method.
The .find()
method returns the first element in an array that satisfies a given condition, and returns undefined
if no elements satisfy the condition.
Here's an example of how to filter an array of objects and return just one object:
index.ts277 chars15 lines
In this example, we define an interface Person
to define the shape of our objects. We have an array of Person
objects called people
, and we use the .find()
method to filter the array and return just one Person
object whose name
property is 'Bob'
.
The person
variable will now contain just one Person
object, even though the .find()
method returns an array with a single element.
gistlibby LogSnag