skip to Main Content

In a React Project, I have an array of objects where I am displaying the values based on certain conditions. I’m able to populate the data with one parameter but, I also want to display with other parameter. Please go through the code below.

const users = [
    { name: "Jack", id: "1" },
    { name: "Lisa", id: "2" },
    { name: "Peter", id: "3" },
    { name: "Roman", id: "4" },
    { name: "Sarah", id: "5" },
    { name: "Eric", id: "6" },
    { name: "Fiora", id: "7" },
  ];

  const filterNames = ({ name }) => {
    return name.toLowerCase().indexOf(searchValue.toLowerCase()) !== -1;
  };

As you can see I’m filtering the array data with “name” parameter which searches exactly as expected but, want to populate records with “id” parameter, like it should work for both “name” and “id”. Any appropraite solution highly appreciated.

Below is the stackblitz link for your reference

Stackblitz Link: https://stackblitz.com/edit/react-search-filter-demo-fmkhv2?file=index.js

2

Answers


  1. You can modify the filterNames function to accept an additional parameter searchParameter, which can be either name or id. Then, check the searchParameter, if it is name, filter the array based on the name property, and if it is id, filter the array based on the id property:

    const users = [
      { name: "Jack", id: "1" },
      { name: "Lisa", id: "2" },
      { name: "Peter", id: "3" },
      { name: "Roman", id: "4" },
      { name: "Sarah", id: "5" },
      { name: "Eric", id: "6" },
      { name: "Fiora", id: "7" }
    ];
    
    const filterData = (searchValue, searchParameter) => {
      return users.filter(user => {
        const value = user[searchParameter].toLowerCase();
        return value.includes(searchValue.toLowerCase());
      });
    };
    
    //pass name
    const nameResults = filterData("sarah", "name");
    console.log(nameResults); // [{ name: "Sarah", id: "5" }]
    
    //pass id
    const idResults = filterData("3", "id");
    console.log(idResults); // [{ name: "Peter", id: "3" }]
    Login or Signup to reply.
  2. The filter callback can do anything you want it to do, as long as it returns a truthy value for elements you wish to include.

    const filterNames = ({ name, id }) => {
      const maybeId = parseInt(searchValue, 10)
      return isNaN(maybeId)
        ? name.toLowerCase().includes(searchValue.toLowerCase())
        : id === searchValue
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search