array includes object in typescript

To check if an array includes a particular object in TypeScript, we need to compare each object in the array with the target object using an equality check.

Here is an example:

index.ts
interface Person {
  name: string;
  age: number;
}

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

const targetPerson: Person = { name: "Bob", age: 30 };

const includesObject = persons.some(person =>
  person.name === targetPerson.name && person.age === targetPerson.age
);

console.log(includesObject); // Output: true
397 chars
19 lines

In the above example, we have an array of Person objects named persons. We also have a target object named targetPerson that we want to search for in the persons array. The includesObject variable will be true if the persons array includes the targetPerson object, and false otherwise.

To perform the equality check, we are using the some method of arrays, which returns true if at least one element meets the given condition. In our case, the condition is that the name and age properties of the person object are equal to the corresponding properties in the targetPerson object. We are checking for deep equality, so it will work even if objects have nested properties.

gistlibby LogSnag