尝试按复选框过滤JSON内容

时间:2017-01-23 16:40:37

标签: javascript jquery json

我是JS和JQuery的新手,我试图使用复选框在页面上过滤JSON数据。到目前为止,我已经让它适用于所选的每个复选框。除了我有一个问题。如何更好地编写此代码,以便您选择多个复选框,它会显示两者的数据。以下是我的代码。



//filter data with checkboxes
$('#submitFilter').click(function() {
  var final = '';
  $('.filters:checked').each(function() {
    var values = $(this).val();
    final += values;
  });

  var globalFilterVariable = '';
  var categoryImage = '';

  $.each(product_data, function(i, item) {
    if (final.indexOf("1") >= 0) {
      globalFilterVariable = item.itemGlutenFree;
    } else if (final.indexOf("2") >= 0) {
      globalFilterVariable = item.itemGMOFree;
    } else if (final.indexOf("3") >= 0) {
      globalFilterVariable = item.itemOrganic;
    } else if (final.indexOf("4") >= 0) {
      globalFilterVariable = item.itemLowSodium;
    } else if (final.indexOf("5") >= 0) {
      globalFilterVariable = item.itemBPAFree;
    } else if (final.indexOf("6") >= 0) {
      globalFilterVariable = item.itemKosherSym;
    }

    //convert JSON strings to uppercase for comparison
    var brandLetter = item.itemBrandLetter.toUpperCase();
    var foodService = item.itemDeli.toUpperCase();

    if (globalFilterVariable !== "N" && globalFilterVariable !== "n" && globalFilterVariable !== "" && brandLetter == "C" && foodService == "N") {
      categoryImage += '<div class="col-lg-3 col-md-4 col-sm-6 col-xs-12">' + '<a href="#"' + 'class="showProduct"' + 'data-itemcategory="' + item.itemCategory + '"' + 'data-itempageurl="' + item.itemFullUPC + '"' + 'data-itemgmo="' + item.itemGMOFree + '"' + 'data-itembpa="' + item.itemBPAFree + '"' + 'data-itemgluten="' + item.itemGlutenFree + '"' + 'data-itemlowsodium="' + item.itemLowSodium + '"' + 'data-itemkosher="' + item.itemKosherSym + '"' + 'data-itemorganic="' + item.itemOrganic + '"' + 'data-itemimage="' + item.imageURL + '"' + 'data-itemname="' + item.itemName + '"' + 'data-itemoz="' + item.itemPackSize + '"' + 'data-itemdescription="' + item.itemDescription + '"' + 'data-itemupc="' + item.itemFullUPC + '">' + '<img class="img-responsive img-hover productImagesCategory" src="' + item.imageURL + '">' + '<h3>' + item.itemName + '</h3>' + '</a>' + '</div>';
      console.log(globalFilterVariable);
    }
  });
  $('#imagesCategoryProducts').hide().html(categoryImage).fadeIn('slow');
  closeNav();
});
&#13;
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap-theme.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<form>
  <div class="checkbox">
    <label>
      <input type="checkbox" id="filter-gulten" class="filters" value="1">Gluten Free</label>
  </div>
  <div class="checkbox">
    <label>
      <input type="checkbox" id="filter-non-gmo" class="filters" value="2">Non-GMO</label>
  </div>
  <div class="checkbox">
    <label>
      <input type="checkbox" id="filter-organic" class="filters" value="3">Organic</label>
  </div>
  <div class="checkbox">
    <label>
      <input type="checkbox" id="filter-low-sodium" class="filters" value="4">Low Sodium</label>
  </div>
  <div class="checkbox">
    <label>
      <input type="checkbox" id="filter-bpa-free" class="filters" value="5">BPA Free</label>
  </div>
  <div class="checkbox">
    <label>
      <input type="checkbox" id="filter-kosher" class="filters" value="6">Kosher</label>
  </div>
  <button type="button" id="submitFilter" class="btn btn-primary">Submit</button>
  <button type="button" id="clearFilter" class="btn btn-primary">Clear</button>
</form>
&#13;
&#13;
&#13;

[
   {
      "_id":"57741c92cce3c4c741000002",
      "itemGMOFree":"Y",
      "itemBrandLetter":"C",
      "itemKosherSym":"OU",
      "itemShipper":"N",
      "itemRefridge":"N",
      "itemFrozen":"N",
      "itemPreWeight":"Y",
      "itemDeli":"N",
      "itemGlutenFree":"Y",
      "itemHoliday":"N",
      "itemSeasonBuy":"N",
      "itemScannable":"N",
      "itemUnlabeled":"N",
      "itemPalletWeight":2368.8,
      "itemPalletTiers":11,
      "itemPalletBlocks":17,
      "itemCaseCube":0.29,
      "itemCaseDepth":12,
      "itemCaseWidth":9,
      "itemCaseHeight":4.75,
      "itemCaseWeight":12.4,
      "itemCaseUnits":12,
      "itemPieceCube":0.02,
      "itemPieceDepth":2.88,
      "itemPieceWidth":2.88,
      "itemPieceHeight":4.25,
      "itemPieceWeight":1,
      "itemNetContent":"14",
      "itemFullUPC":"070796400032",
      "itemCountry":"Italy",
      "itemPackSize":"12/14 oz",
      "itemUOM":"OZ",
      "itemDescription":"0",
      "itemName":"test",
      "itemBuildNum":0,
      "itemSuffix":2,
      "itemItem":40003,
      "itemMFG":70796,
      "itemPrefix":0,
      "itemCase_GTIN":30,
      "itemPiece_GTIN":0,
      "imageURL":"test.jpg",
      "itemCommodity":"1120",
      "__v":0,
      "itemLastUpdated":"1/19/2017 9:56:16 AM",
      "itemVendor":0,
      "itemBPAFree":"Y",
      "itemLowSodium":"N",
      "itemOrganic":"N",
   }
]

3 个答案:

答案 0 :(得分:1)

不是100%确定您要完成的任务,但您可以更改复选框的value属性以存储要查找的名称。

然后,您可以获取所有这些已检查值并使用它们来查找所需的过滤器。不确定为什么你的globalFilterVariable是一个字符串,所以我不能走得太远。我只抓住了第零个元素。

// Filter data with checkboxes
$('#submitFilter').click(function() {
  var filters = [];
  $('.filters').find(':checked').each(function() {
    filters.push($(this).val());
  });

  var globalFilterVariable = '';
  var categoryImage = '';

  $.each(product_data, function(i, item) {
    // Figure out what you want to do with the rest of the filters.
    globalFilterVariable = item[filters[0]]; 
   
    // Convert JSON strings to uppercase for comparison
    var brandLetter = item.itemBrandLetter.toUpperCase();
    var foodService = item.itemDeli.toUpperCase();

    if (['N', 'n', ''].indexOf(globalFilterVariable) === -1
          && brandLetter == "C" && foodService == "N") {
      categoryImage += '<div class="col-lg-3 col-md-4 col-sm-6 col-xs-12">'
        + '<a href="#"' + 'class="showProduct" '
          + 'data-itemcategory="' + item.itemCategory + '" '
          + 'data-itempageurl="' + item.itemFullUPC + '" '
          + 'data-itemgmo="' + item.itemGMOFree + '" '
          + 'data-itembpa="'+ item.itemBPAFree + '" '
          + 'data-itemgluten="' + item.itemGlutenFree + '" '
          + 'data-itemlowsodium="' + item.itemLowSodium + '" '
          + 'data-itemkosher="' + item.itemKosherSym + '" '
          + 'data-itemorganic="' + item.itemOrganic + '" '
          + 'data-itemimage="' + item.imageURL + '" '
          + 'data-itemname="' + item.itemName + '" '
          + 'data-itemoz="' + item.itemPackSize + '" '
          + 'data-itemdescription="' + item.itemDescription + '" '
          + 'data-itemupc="' + item.itemFullUPC + '">'
        + '<img class="img-responsive img-hover productImagesCategory" src="' + item.imageURL + '">'
        + '<h3>' + item.itemName + '</h3>'
      + '</a>'
      + '</div>';
      console.log(globalFilterVariable);
    }
  });
  $('#imagesCategoryProducts').hide().html(categoryImage).fadeIn('slow');
  closeNav();
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap-theme.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<form>
  <div class="checkbox">
    <label><input type="checkbox" class="filters"
                  name="filter-gulten" value="itemGlutenFree">Gluten Free</label>
  </div>
  <div class="checkbox">
    <label><input type="checkbox" class="filters"
                  name="filter-non-gmo" value="itemGMOFree">Non-GMO</label>
  </div>
  <div class="checkbox">
    <label><input type="checkbox" class="filters"
                  name="filter-organic" value="itemOrganic">Organic</label>
  </div>
  <div class="checkbox">
    <label><input type="checkbox" class="filters"
                  name="filter-low-sodium" value="itemLowSodium">Low Sodium</label>
  </div>
  <div class="checkbox">
    <label><input type="checkbox" class="filters"
                  name="filter-bpa-free" value="itemBPAFree">BPA Free</label>
  </div>
  <div class="checkbox">
    <label><input type="checkbox" class="filters"
                  name="filter-kosher"  value="itemKosherSym">Kosher</label>
  </div>
  <button type="button" id="submitFilter" class="btn btn-primary">Submit</button>
  <button type="button" id="clearFilter" class="btn btn-primary">Clear</button>
</form>

这是一种更简单的方法,可以了解如何通过键过滤对象列表。

如果您只想要与退房时完全匹配的项目,请改为使用此表达式:

var filteredItems = sampleItems.filter(function(item) {
  return availableFilters.every(function(filter) {
    return !!item[filter] === activeFilters.indexOf(filter) > -1;
  });
});

var sampleItems = [{
  name : "All",
  gmoFree : 'Y',
  bpaFree : 'Y',
  glutenFree : 'Y',
  lowSodium : 'Y',
  kosherSym : 'Y',
  organic : 'Y'
}, {
  name : "None",
  gmoFree : 'N',
  bpaFree : 'N',
  glutenFree : 'N',
  lowSodium : 'N',
  kosherSym : 'N',
  organic : 'N'
}, {
  name : "GMO and Gluten Free",
  gmoFree : 'Y',
  bpaFree : 'N',
  glutenFree : 'Y',
  lowSodium : 'N',
  kosherSym : 'N',
  organic : 'N'
}];

$('#submitFilter').click(function() {
  var availableFilters = [];
  var activeFilters = [];
  var $filters = $('.filters').each(function() {
    var value = $(this).val();
    availableFilters.push(value);
    if ($(this).is(':checked')) {
      activeFilters.push(value);
    }
  });
  var filteredItems = sampleItems.filter(function(item) {
    return availableFilters.every(function(filter) {
      if (activeFilters.indexOf(filter) > -1) {
        return item[filter] === 'Y';
      }
      return true;
    });
  });
  var $list = $('#list').empty();
  $.each(filteredItems, function(index, item) {
    $list.append($('<LI>').text(JSON.stringify(item)));
  });
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap-theme.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<form>
  <div class="checkbox">
    <label><input type="checkbox" class="filters"
                  name="filter-gulten" value="glutenFree">Gluten Free</label>
  </div>
  <div class="checkbox">
    <label><input type="checkbox" class="filters"
                  name="filter-non-gmo" value="gmoFree">Non-GMO</label>
  </div>
  <div class="checkbox">
    <label><input type="checkbox" class="filters"
                  name="filter-organic" value="organic">Organic</label>
  </div>
  <div class="checkbox">
    <label><input type="checkbox" class="filters"
                  name="filter-low-sodium" value="lowSodium">Low Sodium</label>
  </div>
  <div class="checkbox">
    <label><input type="checkbox" class="filters"
                  name="filter-bpa-free" value="bpaFree">BPA Free</label>
  </div>
  <div class="checkbox">
    <label><input type="checkbox" class="filters"
                  name="filter-kosher"  value="kosherSym">Kosher</label>
  </div>
  <button type="button" id="submitFilter" class="btn btn-primary">Submit</button>
  <button type="button" id="clearFilter" class="btn btn-primary">Clear</button>
</form>
<h2>Results</h2>
<ul id="list"></ul>

答案 1 :(得分:0)

不知道你在这里尝试做什么,但你可以通过用项目名称替换值来提高循环效率

    <form>
  <div class="checkbox">
    <label>
      <input type="checkbox" id="filter-gulten" class="filters" value="itemGlutenFree">Gluten Free</label>
  </div>
  <div class="checkbox">
    <label>
      <input type="checkbox" id="filter-non-gmo" class="filters" value="itemGMOFree">Non-GMO</label>
  </div>
  <div class="checkbox">
    <label>
      <input type="checkbox" id="filter-organic" class="filters" value="itemOrganic">Organic</label>
  </div>
  <div class="checkbox">
    <label>
      <input type="checkbox" id="filter-low-sodium" class="filters" value="itemLowSodium">Low Sodium</label>
  </div>
  <div class="checkbox">
    <label>
      <input type="checkbox" id="filter-bpa-free" class="filters" value="itemBPAFree">BPA Free</label>
  </div>
  <div class="checkbox">
    <label>
      <input type="checkbox" id="filter-kosher" class="filters" value="itemKosherSym">Kosher</label>
  </div>
  <button type="button" id="submitFilter" class="btn btn-primary">Submit</button>

清除

并使用简单的循环来获取项目键

    $('#submitFilter').click(function() {
  var final = [];
  $('.filters:checked').each(function() {
    var values = $(this).val();
    final.push(values);
  });
  for(var i=0;i<final.length,i++){
    globalFilterVariable = item[final[i]];
   //further statements
  }
});

答案 2 :(得分:0)

查看以下小提琴:https://jsfiddle.net/bxoahfum/

不需要jquery ......我希望它朝着正确的方向发展。

<强> HTML

<input data-filter="gluten"  type="checkbox"> Gluten<br/>
<input data-filter="organic" type="checkbox"> Organic<br/>
<input data-filter="bpa"     type="checkbox"> BPA Free<br/>

<button id="filter">Filter!</button>

<div id="results"></div>

<强> JS

var items = [
  { name : 'product 1', gluten : true, organic : true, bpa : false },
  { name : 'product 2', gluten : true, organic : false,bpa : true  },
  { name : 'product 3', gluten : true, organic : true, bpa : true  }
];

var filters = ['gluten','organic','bpa'];

filter.onclick = function(){

  results.innerHTML = '';

  items.forEach(function(item){

    var show = true;

    filters.forEach(function(filter){

      $el = document.querySelector('[data-filter="'+filter+'"]');
      if($el.checked && !item[filter]) show = false;

    });

    if(show){
      $result = document.createElement('div');
      $result.innerHTML = item.name;
      results.appendChild($result);
    }

  });
};

它是犹太洁食