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.