[英]Need to apply multiple filters to JSON data
在我的項目中,我有一個包含吉他及其相關數據的 JSON 文件。 我正在嘗試創建三個過濾器(品牌、類別和條件),當點擊它們時立即加載適當的數據。 我的函數對一個過濾器非常有效,但我不知道如何將這三個過濾器結合起來。
最初將顯示所有吉他,然后在應用每個過濾器時立即過濾。 我該怎么辦? 我意識到一系列點擊的過濾器是有序的,但目前實現這一點超出了我的技能。
示例 JSON
{
"product_id": "0",
"category": "electric",
"condition": "used",
"justIn": "true",
"brand": "gibson",
"year": "1952",
"code": "456def",
"img1": "../img/sale/gibson/295-1.jpg",
"img2": "../img/sale/gibson/295-2.jpg",
"img3": "../img/sale/gibson/295-3.jpg",
"img4": "../img/sale/gibson/295-4.jpg",
"alt": "gibson guitar",
"title": "Gibson ES-295 1952",
"price": "6000.00",
"description": "A beautiful ES-295 with wear you can't fake! The ES-295 was originally produced from 1952 to 1958 and is best known for being the model played by Scotty Moore with Elvis. This particular example plays well with a fantastic feeling neck! The guitar has heavy finish wear with the beautiful greening that you often see on '50s goldtops. Glaser has refretted the guitar and replaced the tailpiece crossbar. The pickguard is missing.",
"specs": ["Body Wood - Laminated Maple",
"Neck Wood - Mahogany",
"Fingerboard Wood - Rosewood",
"Scale Length - 24.75",
"Nut Width - 1 11/16",
"Pickup(s) - Original P-90s",
"Case - Hard Case"
]
}
過濾點擊監聽器
$("#collapseOne, #collapseTwo, #collapseThree").change("click", e => {
const checkbox = e.target
const key = e.target.getAttribute('data-name')
const id = e.target.id
loadWithFilter(checkbox, key, id)
})
數據加載功能。 基於我提供的 JSON,key = 品牌,value = fender
const loadWithFilter = (checkbox, key, value) => {
$.getJSON("../../json/guitars.json", data => {
let dataArr = data
let filterArr = []
let guitar_data = ""
for(let i in dataArr) {
// data
const image1 = dataArr[i].img1
const alt = dataArr[i].alt
const title = dataArr[i].title
const price = dataArr[i].price
// filters
const id = dataArr[i].product_id
const brand = dataArr[i].brand
const category = dataArr[i].category
const condition = dataArr[i].condition
if (value === brand && $(checkbox).prop("checked") == true) {
cardElements()
}
if ($(checkbox).prop("checked") == false) {
cardElements()
}
function cardElements() {
guitar_data += `<div class="gallery-card" data-brand="${brand}" data-category="${category}" data-condition="${condition}">`
guitar_data += `<img class="more-info img-fluid" src="../${image1}" alt="${alt}" data-id="${id}">`
guitar_data += `<h6>${title}</h6>`
guitar_data += `<p class="text-center"><strong>$ ${price}</strong></p>`
guitar_data += '</div>'
$('#img-gallery').html(guitar_data)
}
}
})
}
您可以使用filter
方法迭代您的數據數組
const data = [{ "product_id": "0", "category": "electric", "condition": "used", "justIn": "true", "brand": "gibson", "year": "1952", "code": "456def", "img1": "../img/sale/gibson/295-1.jpg", "img2": "../img/sale/gibson/295-2.jpg", "img3": "../img/sale/gibson/295-3.jpg", "img4": "../img/sale/gibson/295-4.jpg", "alt": "gibson guitar", "title": "Gibson ES-295 1952", "price": "6000.00", "description": "A beautiful ES-295 with wear you can't fake! The ES-295 was originally produced from 1952 to 1958 and is best known for being the model played by Scotty Moore with Elvis. This particular example plays well with a fantastic feeling neck! The guitar has heavy finish wear with the beautiful greening that you often see on '50s goldtops. Glaser has refretted the guitar and replaced the tailpiece crossbar. The pickguard is missing.", "specs": ["Body Wood - Laminated Maple", "Neck Wood - Mahogany", "Fingerboard Wood - Rosewood", "Scale Length - 24.75", "Nut Width - 1 11/16", "Pickup(s) - Original P-90s", "Case - Hard Case" ] }] data.filter(item => { console.log({ brand: item.brand, condition: item.condition, category: item.category }) })
構建過濾器需要結合各種 javascript 方法(如filter
和map
),請map
以下設置來演示過濾數據的可能設置。
嘗試將過濾器輸入(見演示) new
更改為used
或清除它以查看結果更改。
const resultElem = document.querySelector('#results'); const filtersElem = document.querySelector('#filters'); const products = [ { "product_id": "0", "category": "electric", "condition": "used", "justIn": "true", "brand": "gibson", "year": "1952", "code": "456def", "alt": "used gibson guitar", "title": "Gibson ES-295 1952", "price": "6000.00", "description": "A beautiful ES-295 with wear you can't fake! The ES-295 was originally produced from 1952 to 1958 and is best known for being the model played by Scotty Moore with Elvis. This particular example plays well with a fantastic feeling neck! The guitar has heavy finish wear with the beautiful greening that you often see on '50s goldtops. Glaser has refretted the guitar and replaced the tailpiece crossbar. The pickguard is missing.", }, { "product_id": "0", "category": "electric", "condition": "new", "justIn": "true", "brand": "yama", "year": "1952", "code": "456def", "img1": "../img/sale/gibson/295-1.jpg", "img2": "../img/sale/gibson/295-2.jpg", "img3": "../img/sale/gibson/295-3.jpg", "img4": "../img/sale/gibson/295-4.jpg", "alt": "yama guitar", "title": "new yama ES-295 1952", "price": "6000.00", "description": "A beautiful ES-295 with wear you can't fake! The ES-295 was originally produced from 1952 to 1958 and is best known for being the model played by Scotty Moore with Elvis. This particular example plays well with a fantastic feeling neck! The guitar has heavy finish wear with the beautiful greening that you often see on '50s goldtops. Glaser has refretted the guitar and replaced the tailpiece crossbar. The pickguard is missing.", } ]; const buildResult = ({product_id: id, title, price, brand, category, condition, image1, alt}) => { return `<div class="gallery-card" data-brand="${brand}" data-category="${category}" data-condition="${condition}"> <img class="more-info img-fluid" src="../${image1}" alt="${alt}" data-id="${id}"> <h6>${title}</h6> <p class="text-center"><strong>$ ${price}</strong></p> </div>` }; const filterResults = () => { const currentFilters = [...document.querySelectorAll('.filter')].map(filterElem => ({ field: filterElem.dataset.field, value: filterElem.value })); const productsThatMatchCriteria = products.filter(product => { return currentFilters.every(filter => { return filter.value === '-1' || product[filter.field] === filter.value }) }); const resultsFormattedAtHtml = productsThatMatchCriteria.map(product => buildResult(product)).join(''); resultElem.innerHTML = resultsFormattedAtHtml; }; const loadFilters = (fields) => { const possibleValues = {}; products.forEach(product => { fields.forEach(fieldName => { if (!possibleValues.hasOwnProperty(fieldName)) { possibleValues[fieldName] = new Set(); } possibleValues[fieldName].add(product[fieldName]); }) }); const selectors = Object.keys(possibleValues).map(fieldName => { return `<select class="filter" name="filter[${fieldName}]" data-field="${fieldName}"> <option value="-1">All</option> ${[...possibleValues[fieldName]].map(option => `<option value="${option}">${option}</option>`).join('')} </select>` }).join(''); filtersElem.innerHTML = selectors; document.querySelectorAll('.filter').forEach(filter => { filter.addEventListener('change', e => { filterResults(); }) }) }; loadFilters(['brand', 'year', 'condition']) filterResults();
<h1>Filter</h1> <div> <div id="filters"> </div> </div> <h2>Results</h2> <div> <div id="results"></div> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.