Использование фильтра для массива объектов и элементов Div для объектов - PullRequest
1 голос
/ 04 марта 2020

Вот мой код:

HTML

  <input type="text" id=“search”>
  <div id = “items”></div>

JAVASCRIPT

var items = 
    [ { name: 'toy1', price: '12.00', quantity: 12 } 
    , { name: 'toy2', price:  '1.00', quantity:  5 } 
    , { name: 'toy3', price: '11.00', quantity:  2 } 
    , { name: 'toy4', price:  '1.00', quantity:  2 } 
    ] 

items.filter(name(function)){

});

Вот пример. из того, что я хочу сделать: https://www.w3schools.com/howto/howto_js_filter_lists.asp
В моем случае я хочу, чтобы пользователь мог выполнять поиск по имени, но я застрял на том, что писать внутри функции.
I Я хочу, чтобы каждый из объектов в элементах div был таким, когда пользователь выполняет поиск по имени,
ex: toy4, затем другие элементы div отфильтровываются, и отображается только элемент div, содержащий информацию для toy4.
Я знаю, что фильтр является правильным методом использовать здесь, но я не уверен, как связать пользовательский ввод из поля ввода и «проверить / отфильтровать» элементы div, чтобы отобразить только то, что ищет пользователь, и поместить каждый объект в элементы div.

* Я могу использовать только javascript.

Примечание Я прочитал большинство вопросов, похожих на мои, но они были на языках, которые я еще не выучил или не смог ответить на мой вопрос .

Ответы [ 2 ]

0 голосов
/ 04 марта 2020

Вы можете сделать что-то вроде этого

const persons = [
  {name: 'John Doe'},
  {name: 'Jane Doe'},
  {name: 'Spongebob'},
  {name: 'Patrick Star'}
];

const l = document.querySelector('#list');
const i = document.querySelector('#search');

const displayList = (arr) => {
  arr.forEach(e => {
    l.insertAdjacentHTML('beforeend', `<li>${e.name}</li>`);
  });
}

displayList(persons); // Initialize the list using persons array

i.addEventListener('input', (e) => {
  l.innerHTML = ''; // Clear the list

  // Search for possible match and return it as array
  const searchResult = persons.filter(item => {
    if (item.name.toUpperCase().includes(e.target.value.toUpperCase())) return item; 
  });

  displayList(searchResult); // Display a new list based on searched string
});

https://jsfiddle.net/ha49g0eo/4/

0 голосов
/ 04 марта 2020

В вашей функции фильтра вы можете просто сгенерировать все свои html там, но я бы предпочел держать их отдельно. Мне кажется, что у вас есть 3 разные части:

  • Ваши данные
  • Функция фильтра для фильтрации данных на основе поискового запроса
  • An HTML функция генератора, которая будет генерировать ваши html на основе ваших данных

Вот быстрый способ собрать все вместе

const items = [{
    name: 'toy1',
    price: '12.00',
    quantity: 12
  },

  {
    name: 'toy2',
    price: '1.00',
    quantity: 5
  },
  {
    name: 'toy3',
    price: '11.00',
    quantity: 2
  },
  {
    name: 'toy4',
    price: '1.00',
    quantity: 2
  }
];

/**
* Create a function to generate your elements based
* off the passed in array of data
*/
function makeList(data) {
  // Grab your container
  const container = document.getElementById('items');
  // Clear it (reset it)
  container.innerHTML = '';
  // Iterate through your data and create the elements
  // and append them to the container
  data.forEach(i => {
    const element = document.createElement('div');
    element.innerText = i.name;
    container.append(element);
  });
}

/**
* Create an event listener to react to
* search updates so you can filter the list.
* keyUp is used so that you wait for the
* user to actually finish typing that specific
* char before running. Otherwise, you'll be missing
* a char. (Try changing it to 'keypress' and see what happens)
*/
document.getElementById('search').addEventListener('keyup', function(e) {
  // Get the textbox value
  const searchTerm = e.target.value;
  // If no value, reset the list to all items
  if (!searchTerm) {
    makeList(items);
    return;
  }
  // Filter your list of data
  // based off the searchTerm
  const data = items.filter(i => i.name.toLowerCase().includes(searchTerm.toLowerCase()));
  // Pass the list filtered list of data to your makeList function
  // to generate your html
  makeList(data);
});

// Generate your initial list
makeList(items);
<input type="text" id="search">
<div id="items"></div>

В качестве альтернативы, вы можете просто скрывать элементы в DOM вместо того, чтобы каждый раз восстанавливать список fre sh html.

...