JavaScript使用HTML表单过滤JSON对象



我希望在JSON数组中过滤一个对象列表,当一个HTML复选框被单击。我知道JavaScript的数组。sort()方法,但我如何消除项目基于复选框点击?我需要一个事件侦听器吗?

我的JSON看起来是这样的:

{ "lots" : [
    {
    "name" : "Parking Lot Name",
    "price" : 2,
    "cash" : true,
    "credit" : false,
    "address" : "1234 W Main Ave",
    "center" : {
        "lat" : 67.659414,
        "lng" : -137.414730
    }... etc.

如果我有一个包含复选框的表单,用于根据支付类型消除停车场,我应该如何实现它?我读过关于jQuery array.grep()函数,是吗?

我的页面正在使用这样的JS循环构建:

makeList(){
var self = this;
self.jsonFile = $.ajax({
 type: 'GET',
 url: 'assets/data/default.json',
 dataType: 'json',
 success: function(response) {
   console.log(response);
 }
});
self.jsonFile.done(function(data){
  //Sort low to high by default
  data.lots.sort(function(a, b){
    return(a.price > b.price)
  });
  for (var i = 0; i < data.lots.length; i++) {
    document.getElementById('jsonList').innerHTML +=
      '<li>
        <div id="text">
          <p class="price"> 
            $' + data.lots[i].price +  '.00
          </p>
          <p class="info">' +
            data.lots[i].address +
         '</p>
        </div>
        <form method="get">
          <button type="submit" formaction="https://www.google.com/maps/dir/Current+Location/' +
           data.lots[i].address +
           '">Directions
          </button>
          <button type="submit" formaction="detail-view.html">Details
          </button>
        </form>
      </li>';
  }
});

}

你可以这样消除:你必须绑定一个onchange函数到复选框然后使用下面的方法到那个函数

  data = [{
      "name": "name",
      "location1": "no",
      "description": "description of services"
      },
     {
      "name": "name2",
      "location1": "yes",
      "description": "description of services2"
       },
       {
        "name": "name3",
         "location1": "no",
        "description": "description of services3"
    }
  ];
   b = $.grep(data, function(el, i) {
     return el.location1.toLowerCase() === "yes" 
   });

您可以使用以下命令获取付款类型为"现金"的地块:

var cashLots = data.lots.filter(function(lot){return lot.cash});

作为箭头函数:

var cashLots = data.lots.filter(lot => lot.cash);

最新更新