简体   繁体   English

如何在JavaScript中按名字或姓氏或名字和姓氏精确搜索?

[英]How to search exactly by first or last name or by first and last name in JavaScript?

There is a function, which accepts a text value on each input. 有一个函数,可以在每个输入上接受文本值。

There is an array which is full of user objects 有一个充满用户对象的数组

I need to map through the array and get exact values 我需要遍历数组并获取确切值

For example, if I write 'H' or 'h' I will find only Hanna Montanna, for 'A' or 'a' I will get 'Alexander Castle' and 'Anthony Hopkins' and so on and so force 例如,如果我写“ H”或“ h”,我只会找到汉娜·蒙塔纳,对于“ A”或“ a”,我会得到“亚历山大城堡”和“安东尼·霍普金斯”,依此类推

function foo(value) {
     // code here 
}

 const users = [{ name: 'Alexander Castle', age: 25 }, { name: 'Anthony
 Hopkins', age: 60 }, { name: 'Naomi Kempbell', age: 37 }, { name:
 'Hannah Montanna', age: 19 }];

This could be your solution: 这可能是您的解决方案:

function search(term, users) {
    term = term.toLowerCase();
    return users.filter(u => u.name.toLowerCase().startsWith(term));
}
const users = [{
  name: 'Alexander Castle',
  age: 25
}, {
  name: 'Anthony Hopkins',
  age: 60
}, {
  name: 'Naomi Kempbell',
  age: 37
}, {
  name: 'Hannah Montanna',
  age: 19
}];
console.log(search('a',users));

The above answer is perfectly fine but there is no need to lowercase term parameter and replace it's value with same lowercase value. 上面的答案是完全可以的,但是不需要小写term参数并将其值替换为相同的小写值。 So simply you can write like. 因此,您可以简单地写成。

function search(term, users) {  return users.filter(u => u.name.toLowerCase().startsWith(term.toLowerCase())); }

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

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