[英]Find Object in Array Cross Multiple Properties
So I am playing around trying to build an input that I can type and then show only the objects that have matching text.所以我正在尝试构建一个我可以输入的输入,然后只显示具有匹配文本的对象。 I am getting close but need a little help.
我正在接近但需要一点帮助。 I think what I did works but I believe there might be a better way.
我认为我所做的工作有效,但我相信可能有更好的方法。
So I would expect that a user, in the input could type the following values:所以我希望用户可以在输入中输入以下值:
I think the code I have works for it all, but not sure I like what I did for first and last name.我认为我的代码适用于这一切,但不确定我喜欢我为名字和姓氏所做的事情。 I wonder if I should be using regex instead of what I am doing.
我想知道我是否应该使用正则表达式而不是我正在做的事情。 Thoughts?
想法?
export let customers = [
{
id: 1,
firstName: 'John',
lastName: 'Smith',
email: 'john.smith@test.com',
phone: '7025551234',
},
{
id: 2,
firstName: 'Jonathan',
lastName: 'Harken',
email: 'jonathan.harken@test.com',
phone: '7165551234',
},
{
id: 3,
firstName: 'Zack',
lastName: 'Moss',
email: 'zack.moss@test.com',
phone: '9995551234',
},
];
export const filterList = (suggestions, searchValue) => {
return suggestions.filter((sug) => {
let shouldReturn = false;
for (const [key, keyValue] of Object.entries(sug)) {
if (key !== 'id') {
let keyV = keyValue.toLowerCase();
let hasSpace = searchValue.indexOf(' ') > -1;
if (!hasSpace && keyV.indexOf(searchValue) > -1) {
shouldReturn = true;
}
if (hasSpace) {
let split = searchValue.split(' ');
switch (key) {
case 'firstName':
if (keyV.indexOf(split[0]) > -1) {
shouldReturn = true;
}
break;
case 'lastName':
if (keyV.indexOf(split[1]) > -1) {
shouldReturn = true;
}
break;
default:
break;
}
}
}
}
if (shouldReturn) {
return sug;
} else {
return null;
}
});
}
I just think something is off.我只是觉得有些不对劲。
This is simpler version should behave like your function.这个更简单的版本应该像你的函数一样。
let customers = [{ id: 1, firstName: 'John', lastName: 'Smith', email: 'john.smith@test.com', phone: '7025551234', }, { id: 2, firstName: 'Jonathan', lastName: 'Harken', email: 'jonathan.harken@taest.com', phone: '7165551234', }, { id: 3, firstName: 'Zack', lastName: 'Moss', email: 'zack.moss@test.com', phone: '9995551234', }, ]; function filterByValue(objectList, searchValue) { const tokens = searchValue.toLowerCase().split(' '); return Object.values(objectList).filter(entry => { return Object.values(entry).some(entryValue => { if (typeof(entryValue) !== 'string') return false; entryValue = entryValue.toLowerCase(); return tokens.every(token => entryValue.includes(token)); }) }) } console.log(filterByValue(customers, '.com')) console.log(filterByValue(customers, '555 234')) console.log(filterByValue(customers, 'John 555')) console.log(filterByValue(customers, 'John test .com'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.