Reputation: 386
How to make a function that finds data of array of object without giving exact search value that matches with value of object.
For example my array is :
const array =
[{
"name": "Max Messi",
"age": 21,
"gender": "male"
},
{
"name": "tina baidya",
"age": 10,
"gender": "female"
},
{
"name": "tina shrestha",
"age": 100,
"gender": "female"
}
]
Now i want a function to return all the data that has name
"tina" in it.
I tried using array.filter()
method but it requires exact search name. Like i need to type tina shrestha
instead of just tina
this is what I had tried:
const array =
[{
"name": "Max Messi",
"age": 21,
"gender": "male"
},
{
"name": "Lina baidya",
"age": 10,
"gender": "female"
},
{
"name": "tina shrestha",
"age": 100,
"gender": "female"
}
]
function findData(data, id){
const found = data.filter(element => element.name === id)
return found
}
console.log(findData(array, "tina"))//logs empty array as i need to type full search value
So how can i make the function that searches json data without putting exact value.
Upvotes: 2
Views: 735
Reputation: 6380
You can try using the includes() method like so:
const array = [
{
"name": "Max Messi",
"age": 21,
"gender": "male"
},
{
"name": "Lina baidya",
"age": 10,
"gender": "female"
},
{
"name": "tina shrestha",
"age": 100,
"gender": "female"
}
]
const findData = (data, searchParam) => {
return data.filter(element => element.name.includes(searchParam.toLowerCase()));
}
const results = findData(array, "tin");
console.log(results);
However, it won't work if you search for example tina2
or tinathy
so it doesn't cover all edge-cases!
Upvotes: 1
Reputation: 85132
You're almost there, you just need to check if the name includes your string, rather than being equal to it:
const found = data.filter(element => element.name.includes(id))
Upvotes: 4