Как удалить объект и массив в a for Each l oop на основе оператора if (Система фильтрации с использованием Jquery / ES5) - PullRequest
0 голосов
/ 29 апреля 2020

Итак, я создаю систему сортировки / фильтрации, которая будет использоваться в интернет-магазине, и я использовал массив для имитации ответа API. Когда страница загружается впервые, она генерирует продукты на основе информации в массиве. У меня работает сортировка цен, но в настоящее время я борюсь с фильтром поставщиков.
Я выбрал поставщика по выбору пользователя, сохранил его в переменной с именем filterVendorText, затем в for-each l oop попытался проверить его по поставщику в массиве allProducts, но проблема в том, что он всегда не возвращает товаров.

Я также поместил его в codepen . Любые советы по улучшению также приветствуются. Спасибо.

// The products
let allProducts = [
  {id: 452, title: "Gold Flower", price: '5.50', additional_info: "<span id='numberOfShots'>5</span><span id='Size'10</span><span id='Type'>High quality</span><span id='Effect'>sizzle</span>", vendor: "Vendor B"},
  
  {id: 766, title: "Blue Tail", price: '6.50', additional_info: "<span id='numberOfShots'>30</span><span id='Size'>0</span><span id='Type'>Extreme quality</span><span id='Effect'>bang</span>", vendor: "Vendor A"},
  
  {id: 345, title: "Dragon Tail", price: '2.50', additional_info: "<span id='numberOfShots'>15</span><span id='Size'>0</span><span id='Type'>High quality</span><span id='Effect'>trail</span>", vendor: "Vendor C"}, 
  
  {id: 61, title: "Crackling Flower", price: '1.20', additional_info: "<span id='numberOfShots'>10</span><span id='Size'>0</span><span id='Type'>Average quality</span><span id='Effect'>bang</span>", vendor: "Vendor B"}
]


let productsArrayGrid = []
let filteredProductsArray = []
// When the page first load create items
$( document ).ready(function() {

  const createItems = (item, index) => {
    productsArrayGrid.push(`  
      <li class="grid__item">
        <img src="https://via.placeholder.com/200x100" alt="b">
        <p>title: ${item.title}</p>
        <p>vendor: ${item.vendor}</p>
          <div class="price-item--regular">
            <span>£${item.price}</span>
          </div>
      </li>`)
  }

  allProducts.forEach(createItems)
  $('ul#grid > li').remove()
  $('ul#grid').prepend(productsArrayGrid)
})


// Takes users inpout and decides 
// what filter function to run
let userInputPrice;
let filterVendorText;

const filterUserInput = () =>{
  filterVendorText = $("#FilterVendor option:selected").text()
  if(filterVendorText !== "All Vendors"){
      filterItem()
    }
  userInputPrice = $("#FilterPrice option:selected").text()
  if (userInputPrice === "Price, low to high") {
    descToAscending()
  } else if(userInputPrice === "Price, high to low") {
    ascendingToDesc()
  } else {
  // Resets to normal
  $('ul#grid > li').remove()
  $('ul#grid').prepend(productsArrayGrid)
  }

}

  // Filter/Sort functions below:

  // price low to high filter
  const descToAscending = () => {
    var productsContainer = document.getElementById('Collection');
    var els = Array.prototype.slice.call(document.querySelectorAll('#Collection ul > .grid__item'));
    els.sort(function (a, b) {
      return a.querySelector('#Collection ul .price-item--regular > span').innerHTML.substring(1) - b.querySelector('#Collection ul .price-item--regular > span').innerHTML.substring(1);
    });
    $('#Collection > ul#grid').append(els).html();
  }
  // price high to low filter
  const ascendingToDesc = () => {
    var productsContainer = document.getElementById('Collection');
    var els = Array.prototype.slice.call(document.querySelectorAll('#Collection ul > .grid__item'));
    els.sort(function (a, b) {
      return b.querySelector('#Collection ul .price-item--regular > span').innerHTML.substring(1) - a.querySelector('#Collection ul .price-item--regular > span').innerHTML.substring(1);
    });
    $('#Collection > ul#grid').append(els).html();
  }
 
  
  
 
// The function that filters through 
// The products and then creates them
const filterItem = () => {
  // Clear the array  
  productsArrayGrid.length = 0
  
    const createItems = (item, index) => {
     let filterVendor;
     if(item.vendor === filterVendorText) {
       filterVendor = item.vendor
     } else if (item.vendor === undefined){
       // remove item so it's not rendered to the page
       item.splice(index, 1);
     }
      
      filteredProductsArray.push(`  
        <li class="grid__item">
          <img src="https://via.placeholder.com/200x100" alt="b">
          <p>title: ${item.title}</p>
          <p>vendor: ${filterVendor}</p>
            <div class="price-item--regular">
              <span>£${item.price}</span>
            </div>
        </li>`)
    }

  allProducts.forEach(createItems)
  
  // Remove products from the page
  $('ul#grid > li').remove()
  // Add the products back according to 
  // User input from the fiilters
  $('ul#grid').prepend(filteredProductsArray)
}
#filters{
  margin: 10px 15px;
  display: flex;
  justify-content: space-between;
}
#grid{
  display: flex;
  justify-content: space-between;
}

ul{
  padding: 0px;
}
li{
  margin: 5px 15px;
  list-style: none;
}
<div class="container">
  <div id="filters">
    <select class="filter" name="FilterPrice" id="FilterPrice">
      <option value="all">Price</option>
      <option value="price-ascending">Price, low to high</option>
      <option value="price-descending">Price, high to low</option>
    </select>
    <select class="filter" name="FilterVendor" id="FilterVendor">
      <option value="all">All Vendors</option>   
      <option value="Vendor A">Vendor A</option>            
      <option value="Vendor B">Vendor B</option>                 
      <option value="Vendor C">Vendor C</option>
    </select>
    <select class="filter" name="FilterVendor" id="FilterShots">
      <option value="all">No. of shots</option>   
      <option value="5">5</option>
      <option value="10">10</option>
      <option value="15">15</option>
      <option value="20">20</option>
      <option value="25">25</option>
      <option value="30">30</option>
    </select>
    <select class="filter" name="effect" id="FilterEffect">
      <option value="all">Effect</option>   
      <option value="sizzle">sizzle</option>            
      <option value="bang">bang</option>                 
      <option value="trail">trail</option>
      <option value="trail">snake</option>
    </select>
    <input id="applyInput" 
           type="submit"
           value="Apply filter" 
           onclick="filterUserInput();" />
  </div>
  <div id="Collection">
    <ul id="grid">
     
    </ul>
  </div>
</div>
...