0

I am making a search bar, to filter a table I have. I know how to filter an array of objects by a specific value, for example "team" values see code below:

const characters = [
  { name: 'Batman', team: 'Justice League' },
  { name: 'Hulk', team: 'Avengers' },
  { name: 'Flash', team: 'Justice League' },
  { name: 'Iron Man', team: 'Avengers' },
  { name: 'Avengers', team: 'X-Force' }
];

const avengers = characters.filter(character => character.team === 'Avengers');

My Questions is, what if want to filter it by any of the properties in the object contains the value Avengers? without doing it the manual way like:

  const avengers = characters.filter(character => character.team === 'Avengers' || character.name === 'Avengers');

The reason why I don't want to do it this way is because some of the objects are quite large...

Hanskrogh
  • 86
  • 6
  • 2
    `Object.values()` + `Array.prototype.some()`, or a simple `for...in...` / `for...of...` loop – Andreas May 18 '21 at 10:24
  • Does this answer your question? [Filter array of objects whose any properties contains a value](https://stackoverflow.com/questions/44312924/filter-array-of-objects-whose-any-properties-contains-a-value) – Heretic Monkey May 18 '21 at 10:38

1 Answers1

2

You can do

  const avengers = characters.filter(character => !!Object.values(character).find(e => e === 'Avengers'));
Siddharth
  • 450
  • 4
  • 10