Home > Enterprise >  search items from an array with multiple categories in ReactJS
search items from an array with multiple categories in ReactJS

Time:07-11

I have created a react application which display some data using map method later I have added a input search field so that I must be able to see a particular data from multiple data, now what I have troubled with is that, if I'm adding a particular category to filter I'm successfully able to display them, but I'm unable to show remaining category data from search.

How can I improve my code to be able to search data among multiple category of items.

Check my code below and tell me how I can perform the functionality I want to create.

This is how I displayed my array data

{APIData
.filter(data=>data.companyName.toLowerCase().includes(search.toLowerCase())
.map((data,id)=>{
                    return(
                        <>
                        <tbody key={id}>
                            <tr>{data.companyName}</tr>
                            <tr>{data.companyNumber}</tr>
                            <tr>{data.uniqueNumber}</tr>
                            <tr>{data.lineofBusiness}</tr>
                        </tbody>
                        </>
                            )
                        })}

This is my search field:

const [search, setSearch] = useState('');
    <input type="text" value={search} onChange={(e)=> setSearch(e.target.value)}/>

These are my categories in the APIData:

let { id, image, companyName, email, companyNumber, lineofBusiness,address,
                pincode,area,city,state,country } = data;

With my knowledge over ReactJS I was able to filter a single category of my array using this method while data render:

.filter(data=>data.companyName.toLowerCase().includes(search.toLowerCase())

In the above code if I change the companyName to any other array I'm able to search the individual category, but I want to get all the categories to be able to search from alltogether.

How can I do this please help me get over the problem and if you need any further info needed to solve my problem ask me.

CodePudding user response:

You can use this filter method, as it will filter on all the data properties.

.filter(data => 
  Object.values(data).some(value => value.toLowerCase().includes(search.toLowerCase()))
)

CodePudding user response:

You can use the filter method to find all the matched data with a litle function

rows.filter(data => {
    let isValid = false;
    rows.forEach((row) => {
        if(rows.toLowerCase().includes(search.toLowerCase()) {
              isValid = true;
              return;
        }
     })
     if(isValid){
         return data;
     }
     return null
})

I hope it will help you!

  • Related