I have the JSON data pattern coming from API in the below way. I was able to filter the data with body
key. I'm trying to implement the search functionality which should search all the array of objects irrespective of key
based on user input. Could someone please guide how to achieve this. I tried using nested for loop to get the individual key but not luck.
[
{
"postId": 1,
"id": 1,
"name": "id labore ex et quam laborum",
"email": "[email protected]",
"body": "laudantium enim quasi est quidem magnccusantium"
},
{
"postId": 1,
"id": 2,
"name": "quo vero reiciendis velit similique earum",
"email": "[email protected]",
"body": "est natus enim nihil est dolore is et"
}
...
]
Key based search logic that I'm currently using
const filteredData = data.filter(item =>
item.body.includes(searchTerm.value)
);
this.setState({ filteredData: filteredData });
I created a working example using Sandbox. Could anyone please guide how to achieve the Search results from entire array of Objects?
Try this:
const filteredData = data.filter(item => Object.values(item).some(val => val.toString().includes(searchTerm.value)));