[英]JavaScript how to find data of array of object without giving exact search value that matches with value of object
How to make a function that finds data of array of object without giving exact search value that matches with value of object.如何制作一个 function 来查找 object 数组的数据,而不给出与 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.现在我想要一个 function 返回所有
name
“tina”的数据。
I tried using array.filter()
method but it requires exact search name.我尝试使用
array.filter()
方法,但它需要准确的搜索名称。 Like i need to type tina shrestha
instead of just tina
就像我需要输入
tina shrestha
而不是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.那么我怎样才能使搜索 json 数据的 function 没有输入确切的值。
You can try using the includes() method like so:您可以尝试使用include()方法,如下所示:
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!但是,如果您搜索例如
tina2
或tinathy
,它将不起作用,因此它不会涵盖所有边缘情况!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.