React filter array of object by any field
Suppose I have an array of objects that have
name: id: school: address:
I know how to filter by one category, such as
data.filter(data => data[name].includes("Lake"))
to get all the objects whose name includes the word Lake.
But is there a way to filter the data to get all object where any of the fields includes the word?
data.filter(data => data.includes("Lake"))
doesn't work, I already tried.
Thank you!
Solution 1:
const arr = [
{ id: 1, name: "name_1", school: "school_1", address: "address_1" },
{ id: 2, name: "lake", school: "school_2", address: "address_2" },
{ id: 3, name: "name_3", school: "lake", address: "address_3" },
{ id: 4, name: "name_4", school: "school_4", address: "lake" }
];
const anyKeyFilter = item => obj => Object.values(obj).includes(item);
const filteredArr = arr.filter(anyKeyFilter("lake"));
console.log(filteredArr);
You may use trim()
and .toLowerCase()
if you need it.
Solution 2:
const arr = [
{ id: 1, name: "name_1", school: "school_1", address: "address_1" },
{ id: 2, name: "lake", school: "school_2", address: "address_2" },
{ id: 3, name: "name_3", school: "lake", address: "address_3" },
{ id: 4, name: "name_4", school: "school_4", address: "lake" }
];
const filteredArr = arr?.filter((data) => Object.values(data)?.includes('lake'));
console.log(filteredArr);