objects-array filter and result just be one object type not one object-array in typescript

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.ts
interface Person {
  name: string;
  age: number;
}

const people: Person[] = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 35 },
];

const person = people.find((p) => p.name === 'Bob');

console.log(person); // { name: 'Bob', age: 30 }
277 chars
15 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