如何在javascript中过滤多个对象
我需要从firstname或lastname获得结果, 当前的行为只给我firstname的结果。或者使用如何在javascript中过滤多个对象,javascript,Javascript,我需要从firstname或lastname获得结果, 当前的行为只给我firstname的结果。或者使用filter():)的更好方法也不应该区分大小写 const people = [ { firstName: 'Bob', lastName: 'Smith', status: 'single' }, { firstName: 'bobby', lastName: 'Suxatcapitalizing', status: 'single' }, { fir
filter()
:)的更好方法也不应该区分大小写
const people = [
{ firstName: 'Bob', lastName: 'Smith', status: 'single' },
{ firstName: 'bobby', lastName: 'Suxatcapitalizing', status: 'single' },
{ firstName: 'Jim', lastName: 'bob', status: 'complicated' },
]
const searchString = 'bob'
const found = people.filter(
(person) => new RegExp(searchString, 'i')
.test(
person.firstName || person.lastName
))
console.log(found)
|
运算符返回第一个参数(不是false
、null
、未定义的
、0
或”
),因此此操作仅在person.firstName
中搜索bob
您需要进行两次单独的搜索。为避免重复,请将regexp对象存储在变量中:
const searchString='bob'
const regexp=new regexp(搜索字符串'i')
const found=people.filter(
(person)=>regexp.test(person.firstName)| | regexp.test(person.lastName)
)
console.log(已找到)
const people=[
{姓:“鲍勃”,姓:“史密斯”,状态:“单身”},
{名字:'bobby',姓氏:'SuxatCapitalizating',状态:'single'},
{姓:“吉姆”,姓“鲍勃”,状态“复杂”},
]
const searchString='bob'
const found=people.filter(person=>
(person.firstName.toLowerCase().includes(searchString)||
person.lastName.toLowerCase().includes(searchString))
)
console.log(已找到)
或使用
filter
函数应返回true
或false
,而不是对象。这是你写的方式,但有点出乎意料。这不仅仅是“重复你自己”的情况-原始代码会为数组中的每个元素创建一个全新的RegExp
对象。过早优化是万恶之源。大多数这种性质的重构也会导致优化。@托马斯如果我搜索Bob Smith
它什么也不返回……我如何在搜索中组合这两个词?@BizMAN这是一个问题单独的问题。与正则表达式解决方案相比,它的性能如何?
const found = people.reduce((acc, n) => {
if (
n.firstName.toLowerCase() === searchString
|| n.lastName.toLowerCase() === searchString
) {
acc[n] = acc.push(n);
}
return acc;
}, []);