0

I have an array like:

students:
  0: 
     name: "name1",
     surname: "surname1",
     age: "18"
  1: 
     name: "name2",
     surname: "surname2",
     age: "28"
  2: 
     name: "name3",
     surname: "surname3",
     age: "38"
  // and others...

And i'm trying to make a filter with a input to search in this array of Objects.

I would to filter every field in the array of object, so for example if I write in my input 38, it should return name3, surname3, 38.

The same result i would to obtain if i search name3.

Now I have implemented the filter in this way:

students.filter(student=> student.name.toLowerCase().includes(searchTerm.toLowerCase()) || student.surname.toLowerCase().includes(searchTerm.toLowerCase()) || student.age.toLowerCase().includes(searchTerm.toLowerCase()).

My question is:

How can I do to avoid having to specify the various fields in which to search in an OR?

Thank you

2 Answers 2

2

You could do something like this:

students.filter(student => Object.values(student).some(v => v.toLowerCase().includes(searchTerm.toLowerCase())))
Sign up to request clarification or add additional context in comments.

2 Comments

Object.entries() is an alternate choice if you want the keys as well.
Ooh thank you this could be a solution, I have only a problem with this suggestion.. I have some fields that could be null at the beginning infact if I use this method I receive error Cannot read property 'toLowerCase' of null
1
students.filter((student) => {
  // Destructure student to get values easier.
  const { name, surname, age } = student;

  // Creating an array with all the fields, setting them to lower with map, then find one that
  // satisfies the requirement. If none of them match then find will return undefined. The "!!" converts it to a bool.
  return !![name, surname, age]
    .map((x) => x.toLowerCase())
    .find((x) => x && x.includes(searchTerm.toLowerCase()));
});

Without comments:

students.filter((student) => {
  const { name, surname, age } = student;
  return !![name, surname, age]
    .map((x) => x.toLowerCase())
    .find((x) => x && x.includes(searchTerm.toLowerCase()));
});

Comments

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.