首页 > 解决方案 > 实时搜索对象输入 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..."/>

标签: javascripthtml

解决方案


推荐阅读