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...

2

1 Answer 1

2

You can do

  const avengers = characters.filter(character => !!Object.values(character).find(e => e === 'Avengers'));
Sign up to request clarification or add additional context in comments.

2 Comments

maybe better to use .some instead, as it returns a boolean.
I get the following error when trying to do so: "Uncaught TypeError: Avengers is not a function"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.