如何创建一个函数来查找对象数组的数据,而不给出与对象值匹配的精确搜索值。例如我的数组是:const array = [{ "name": "Max Messi", "age": 21, "gender": "male"},{ "name": "tina baidya", "age": 10, "gender": "female"},{ "name": "tina shrestha", "age": 100, "gender": "female"}]现在我想要一个函数来返回所有包含“tina”的数据name。我尝试使用array.filter()方法,但它需要精确的搜索名称。就像我需要打字tina shrestha而不是仅仅tina这是我尝试过的: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那么我怎样才能创建搜索 json 数据的函数而不输入确切的值。
2 回答
慕容森
TA贡献1853条经验 获得超18个赞
你就快到了,你只需要检查名称是否包含你的字符串,而不是等于它:
const found = data.filter(element => element.name.includes(id))
红糖糍粑
TA贡献1815条经验 获得超6个赞
您可以尝试使用includes()方法,如下所示:
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);
tina2
但是,如果您搜索 example或tinathy
因此它不涵盖所有边缘情况,它将不起作用!
添加回答
举报
0/150
提交
取消