Home > Net >  REACT filtering objects in array based on values
REACT filtering objects in array based on values

Time:08-22

i have an array of objects employees that looks something like this :

 [
{ nameAR:"عاصم ماجد شوشاري",nameEN:"aasem majed shoshari",age:"23",maritalStatus:"single" },
{ nameAR:"عاصم ماجد شوشاري",nameEN:"aasem majed shoshari",age:"23",maritalStatus:"single" },
{ nameAR:"عاصم ماجد شوشاري",nameEN:"aasem majed shoshari",age:"23",maritalStatus:"single" },
{ nameAR:"عاصم ماجد شوشاري",nameEN:"aasem majed shoshari",age:"23",maritalStatus:"single" },
{ nameAR:"عاصم ماجد شوشاري",nameEN:"aasem majed shoshari",age:"23",maritalStatus:"single" },

]

assuming that those objects are not the same and are different data, i want to filter this array onChange based on matching object values to the search field value:

  const handleSearch = (e) => {
    const filteredArray = employees.filter((emp) => 
      Object.values(emp).map((value) => {
        return value.includes(e.target.value);
      })
);
    console.log(filteredArray);
  };

  ...
        <input
          type="search"
          placeholder="Search employees.."
          className="searchInput"
          onChange={handleSearch}
        />
  ...

but filteredArray returns an empty array, i want it to return the objects that any of its values characters matches search input value characters, how to do that?

CodePudding user response:

This is how the handleSearch function should be in your case:

const handleSearch = (e) => {
  const searchKey = e.target.value;
  return employees.filter((employee) =>
    Object.values(employee).join(' ').includes(searchKey)
  );
};

Object.values(employee) will result in:

['عاصم ماجد شوشاري', 'aasem majed shoshari', '23', 'single']

Object.values(employee).join(' ') will result in:

'عاصم ماجد شوشاري aasem majed shoshari 23 single'

Object.values(employee).join(" ").includes(searchKey) to check if that string has your searchKey.

Note that your employees array's objects have the same key-values pairs, so even if you run this code that is correct you will either see the full list of employees or none.

  • Related