Home > database >  How can i filter data from array in object react
How can i filter data from array in object react

Time:10-26

this is my data

"tester": [{ "title": "test1", "id": "1", "description": "abcdefg", "photos": ["1.jpg","2.jpg"], "tags": ["Sample","Help","OMG","Assignment","Bug"] };

my solution right now but it can not search each letter in the tags array

const fliterdata = trips.filter((filter) => {
        if (searchTerm === '') {
            return filter;
        } else {
            return filter.title.toLowerCase() && //search word in title
                filter.description.toLowerCase() && //search word in description
                filter.tags.map((tag, index) => filter.tags[index].toLowerCase()).includes(searchTerm); //search each letter in the tags array
        }
    });

CodePudding user response:

You forgot to actually compare the strings. You can do it elegantly by combining all values to match into a single array like this:

const searchTermLowercased = searchTerm.toLowerCase();
const filterdata = searchTerm === '' ? trips : trips.filter(
    ({ title, description, tags }) => [title, description, ...tags].some(
        value => value.toLowerCase().includes(searchTermLowercased)
    )
);
  • Related