I have a FlatList that renders following data successfully.
const messages = [
{
"user": {
"id": 4,
"userId": "1561652136"
},
"resultsCount": 9,
"results": [
{
"id": 252,
"senderId": 147,
"recipientId": 4,
"body": "some text"
},
{
"id": 253,
"senderId": 147,
"recipientId": 4,
"body": "some other text"
}
]
},
{
"user": {
"id": 14,
"userId": "6155616153"
},
"resultsCount": 17,
"results": [
{
"id": 275,
"senderId": 147,
"recipientId": 145,
"body": "can you find also this text"
},
{
"id": 276,
"senderId": 145,
"recipientId": 147,
"body": "you should find this text"
}
]
}
]
I want to filter messages according to user input. So, I am trying to achieve search functionality.
if (userInput) {
const newData = messages.filter(message => {
const messageData = message ? message.toUpperCase() : ''.toUpperCase()
const textData = text.toUpperCase()
return messageData.indexOf(textData) > -1
})
setFilteredData(newData)
} else {
setFilteredData(messages)
}
Above code is not working since user should only be able to search in the body.
For example if the userInput is can, newData should be like that:
[
{
"user": {
"id": 14,
"userId": "6155616153"
},
"resultsCount": 17,
"results": [
{
"id": 275,
"senderId": 147,
"recipientId": 145,
"body": "can you find also this text"
},
{
"id": 276,
"senderId": 145,
"recipientId": 147,
"body": "you should find this text"
}
]
}
]
Here's one way to aggregate the bodies of each message's results and test them for the presence of a given text. This assumes the availability of the messages array, per your original posted code.
function findMessages(text) {
return messages.filter(function(message) {
const bodies = message.results.map(result => result.body).join('\n');
return bodies.includes(text);
});
}
console.log(findMessages("can"));