0

If I have a TypeScript Array of

things: Things[]

export type Party = {
  id: string;
  name: string;
};

export type Things = {
  party: Party;
  id: number;
  ...more stuff
};

how can I check if the things array has a Party with a certain name?

Something like included = things.includes(party.name.includes("Bob")) or included = things.some(party.name("Bob"))

Wayneio
  • 3,466
  • 7
  • 42
  • 73

2 Answers2

2

You are almost there:

const included = things.some(thing => thing.party.name === "Bob")

You need to provide a function to some. That function will be called for every element and should return something that (when coerced to a boolean) indicates whether the element matches your criteria or not. In this case we pass a function that returns true if an element's party property has a name property that is equal to "Bob".

CherryDT
  • 25,571
  • 5
  • 49
  • 74
1

You could use .find

const included = !!things.find(thing => thing.party.name === 'Bob')

P.S !! before the statement makes included as a boolean

Georgy
  • 1,879
  • 2
  • 9
  • 14