简体   繁体   English

JavaScript 如何在不提供与 object 值匹配的确切搜索值的情况下查找 object 数组的数据

[英]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'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))

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!但是,如果您搜索例如tina2tinathy ,它将不起作用,因此它不会涵盖所有边缘情况!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM