javascript - 实时搜索对象输入 vanilla JS
问题描述
要获取此数组中的对象,此函数从对象数组中过滤名称和类别,这里的问题是当我输入例如:“jamm”(多个“m”)时,我得到一个空数组,即使输入的词是正确的。我的目标是匹配正确的单词,无论多少。我认为正则表达式可以解决这个问题。提前致谢
var fromDB = [
{id: 1, name: 'Almendras', category: 'Frutos secos', price: 25, amount: 0, description: 'asd'},
{id: 2, name: 'Nueces', category: 'Frutos secos', price: 10, amount: 0, description: 'asd'},
{id: 3, name: 'Mermelada', category: 'Jam', price: 15, amount: 0, description: 'asd'},
{id: 4, name: 'Alfajor', category: 'Sweet', price: 20, amount: 0, description: 'asd'},
{id: 5, name: 'Queso', category: 'UwU', price: 45, amount: 0, description: 'asd'},
{id: 6, name: 'Arandanos', category: 'Fruta', price: 50, amount: 0, description: 'asd'},
{id: 7, name: 'Maracuya', category: 'Fruta', price: 50, amount: 0, description: 'asd'},
{id: 8, name: 'Chocolate', category: 'Sweet', price: 50, amount: 0, description: 'asd'},
{id: 9, name: 'Mascarpone', category: 'UwU', price: 50, amount: 0, description: 'asd'}
];
const input = document.querySelector('input');
input.addEventListener('input', updateValue);
function updateValue(e) {
realTimeInputValue = e.target.value.toLowerCase();
let productsMatch = fromDB.filter(x => x.name.toLowerCase().includes(realTimeInputValue))
if(productsMatch.length){
console.log(productsMatch)
} else {
let categoriesMatch = fromDB.filter(x => x.category.toLowerCase().includes(realTimeInputValue))
console.log(categoriesMatch);
}
}
<input type="text" placeholder="Search product..."/>
解决方案
推荐阅读
- javascript - 我收到 ReferenceError: html is not defined
- javascript - 重新排序 jquery 数组从给定位置开始
- c++ - 交叉编译时Jetson工具链文件夹结构和libgomp链接器错误
- vba - 如何从大型 Excel 文件中聚合行
- c++ - std::sort / 在测试代码中工作,但不能推导出模板
- c# - 列表集合循环
- java - 如何使用 Spring Rest Docs 记录对象列表
- http - SoapUI 来管理 cookie
- javascript - 类似对象的数组,不显示特定值,而是显示整个数组。(JavaScript)
- c - 为什么给共享内存中的 memcpy 一个分段错误