需要将多个过滤器应用于JSON数据

杰夫·S

在我的项目中,我有一个由吉他及其相关数据组成的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,键=品牌,价值=护舷板

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)
        }
      }
    })
  }

马丁·德夫

构建过滤器需要结合各种javascript方法(例如filtermap),并检查以下设置,以演示用于过滤数据的可能设置。

尝试将过滤器输入(请参见演示)从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>

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

Servlet过滤器-不要将过滤器应用于特定过滤器

Ionic将多个过滤器应用于列表

将多个过滤器应用于表 reactjs

将片段过滤器应用于多个源

基于用户输入将多个过滤器应用于数据框的pythonic方法

熊猫-创建多个过滤器并应用于数据框

将过滤器应用于列表并显示数据

使用 lappy 将过滤器函数应用于多个数据集时收到错误

如何将过滤器功能应用于多个列表中的项目?

JDI将类过滤器应用于多个类

将多个过滤器应用于pandas DataFrame或Series的有效方法

如何将过滤器应用于具有多个“ AND”条件的DataView

将多个过滤器应用于Google Charts仪表盘

Elasticsearch:如何将多个过滤器应用于相同的值?

Powershell应用于Outlook Com对象-多个过滤器

在Laravel 5中将多个过滤器应用于表

使用JavaScript将多个过滤器类别应用于<li>的列表

根据条件将过滤器应用于数据框

巴特沃斯过滤器应用于熊猫数据框的一列

查询数据框,但仅将过滤器应用于列值不是NaN的行

如何将dplyr过滤器应用于数据帧列表?

将开始和结束时间作为过滤器应用于数据帧

使用过滤器将数据框应用于不同变量

如何转换此数据框并将过滤器应用于单元格?

如何将Delphi ADOTable过滤器应用于日期数据类型

使用熊猫将过滤器列表应用于来自列表的数据框

将中值过滤器应用于2轴的数据

如何创建将不同过滤器应用于数据框的循环

如何将过滤器应用于成对?