Keyz23
Keyz23

Reputation: 81

ReactJS: Filtering in each objectof array

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

Upvotes: 0

Views: 58

Answers (2)

szilagyi.sandor
szilagyi.sandor

Reputation: 214

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()));
});

Upvotes: 1

Lueton
Lueton

Reputation: 171

You could do something like this:

students.filter(student => Object.values(student).some(v => v.toLowerCase().includes(searchTerm.toLowerCase())))

Upvotes: 2

Related Questions