0

I'm learning react native and currently displaying a FlatList of objects from a JSON file.

    data = [
{
  "id": 1,
  "name" : "Joe",
  "city" : "Sacramento"
},
{
  "id": 2,
  "name" : "Sam",
  "city" : "Chicago"
},

];

I'm trying to implement a search bar such that if the I entered "Sa" it would return both 'Sam' and 'Sacramento'.

It seems like every single tutorial on the web uses the same exact code to do array filtering, which is something like this:

const searchFilter = (text) => {
    if (text) {
        const newData = data.filter((item) => {
            const itemDataName = item.name ? item.name.toUpperCase() : ''.toUpperCase();
            const textDataName = text.toUpperCase();
            return itemDataName.indexOf(textDataName) > -1;
        });
        setFilterData(newData);
        setSearch(text);
    } else {
        setFilterData(data);
        setSearch(text);
    }
}

This works great for searching a single field such as 'name', but doesn't search 'city'. How do I correctly search across multiple key value pairs in the objects inside the data array? I feel like I'm missing something basic.

  • Can you give a minimum working example in codesnadbox ? As we need to pass the value of the key along with the items, You can use the inbuilt regex matching of JS to match the pattern, so as per your case, you can get the text from the search field and append .* to the end of the string and use the itemDataName.match(regex) and that should help for all the values, but you should pass which key to search and then the value with the regex – SARAN SURYA Jul 08 '22 at 04:11
  • Actually it is a JS problem, not specific to react-native. The question could be adapted. See related answer https://stackoverflow.com/questions/47653927/javascript-searching-for-a-string-in-the-properties-of-an-array-of-objects – benek Sep 12 '22 at 06:40

1 Answers1

0
    const newData = data.filter(  function(item) {
        if (item.city.toLowerCase().includes(text.toLowerCase())) {
            return item;
        }
        if (item.name.toLowerCase().includes(text.toLowerCase())) {
            return item;
        }
    } );

I reworked the filter to the above and its working great. Just in case any other newbies find this.