Nono.MA

Find an array item by property value in TypeScript

JUNE 12, 2022

Here's how to find an item with a matching property value. We're querying an array of items in search of an entry, in this case, looking for a person by name and then retrieving their age.

// Define the Person type
type Person = {
    name: string;
    age: number;
}

// Define an array of persons
const people: Person[] = [
    {
      name: 'James',
      age: 24,
    },
    {
      name: 'Claire',
      age: 13,
    },
    {
      name: 'John',
      age: 42,
    }
  ];
  
  const person = people.find(p => p.name == 'John') as Person;
  // {
  //   name: 'John',
  //   age: 42,
  // }
  
  console.log(`${person.name} is ${person.age}.`);
  // John is 42.

Before you go

If you found this useful, you might want to join my newsletter; or take a look at other posts on TypeScript.

BlogCodeTypescript