如何使用搜索过滤器表单搜索JSON数组?

时间:2013-12-31 01:14:24

标签: javascript jquery arrays json

我有一个JSON数组和一个带有多个过滤器的搜索表单。在此搜索表单中,我有4个选择下拉字段用于过滤。如何根据用户选择的内容搜索JSON数组,然后在点击提交按钮后显示结果?

例如,如果用户选择" Burger"在"食物选择下拉"田野"可口可乐"在"饮料选择下拉"领域。我希望能够显示所有提供这两种商品的餐厅。这可能吗?

var restaurants = [
            {"restaurant" : { "name" : "McDonald's", "food" : "burger", "drink" : "coke", "content" : "Lorem ipsum dolor sit amet" }},
            {"restaurant" : { "name" : "KFC", "food" : "chicken", "drink" : "pepsi", "content" : "Lorem ipsum dolor sit amet" }},
            {"restaurant" : { "name" : "Pizza Hut",  "food" : "pizza", "drink" : "sprite", "content" : "Lorem ipsum dolor sit amet" }},
            {"restaurant" : { "name" : "Dominos",  "food" : "pizza", "drink" : "root beer", "content" : "Lorem ipsum dolor sit amet" }},
            {"restaurant" : { "name" : "Popeyes",  "food" : "chicken", "drink" : "mist", "content" : "Lorem ipsum dolor sit amet" }}
          ];

3 个答案:

答案 0 :(得分:2)

过滤数组的一种方法是以下

function filter( restaurants, food, drink) { 

    var result = [];

    for( var i= 0, len = restaurants.length; i < len; i++) {
        var el = restaurants.restaurant[i];

        if( el.food === food && el.drink === drink ) {
            result.push( el );
        }
    }

    return result;
}

更实用的方式

您可以使用Array原型

中定义的过滤器方法
function customFilter(food, drink) {
   return function(el) {
      var r = el.restaurant;
      return r.food === food && r.drink === drink;
   }
}

restaurants.filter( customFilter('Burger', 'Coke') );

复杂的通用过滤器

function customFilter(values) {
   return function(el) {
      var r = el.restaurant;
      var keys = Object.keys( values );
      var answer = true;

      for( var i = 0, len = keys.length; i < len; i++) {
          if( r[keys[i]] !== values[keys[i]] ) {
              answer = false;
              break;
          }
      }

      return answer;
   }
}

restaurants.filter( customFilter({'food':'Burger', 'drink': 'Coke'}) );    

答案 1 :(得分:1)

JavaScript 的原生Array.prototype.filter接受功能。您只想在用户选择输入时生成此功能,例如

function filter(a, food, drink) {
    food = food ? food.toLowerCase() : 0;
    drink = drink ? drink.toLowerCase() : 0;
    return a.filter(function (e) {
        if (food && e.restaurant.food.toLowerCase().indexOf(food) === -1)
            return false;
        if (drink && e.restaurant.drink.toLowerCase().indexOf(drink) === -1)
            return false;
        return true;
    });
}

filter(restaurants, 'burger', 'coke');
// [{"restaurant":{"name":"McDonald's","food":"burger","drink":"coke","content":"Lorem ipsum dolor sit amet"}}]

答案 2 :(得分:0)

我已经对Igor的回答进行了投票,但是,因为我想在jsfiddle中提供一个完整的例子,所以你去:http://jsfiddle.net/jeffrenaud/JDYMt/

我添加了“Any”选项的可能性,因此特定元素上没有过滤器。

以下是摘要:

HTML:

<label for="food">Food:</label>
<select id="food">
    <option value="">Any</option>
    <option value="burger">Burger</option>
    <option value="chicken">Chicken</option>
    <option value="pizza">Pizza</option>
</select>

<label for="drink">Drink:</label>
<select id="drink">
    <option value="">Any</option>
    <option value="coke">Coke</option>
    <option value="pepsi">Pepsi</option>
    <option value="sprite">Sprite</option>
    <option value="root beer">Root beer</option>
    <option value="mist">Mist</option>
</select>

<ul id="result"></ul>

JavaScript:

var restaurants = [
    {
        "restaurant": {
            "name": "McDonald's",
            "food": "burger",
            "drink": "coke",
            "content": "Lorem ipsum dolor sit amet"
        }
    },
    {
        "restaurant": {
            "name": "KFC",
            "food": "chicken",
            "drink": "pepsi",
            "content": "Lorem ipsum dolor sit amet"
        }
    },
    {
        "restaurant": {
            "name": "Pizza Hut",
            "food": "pizza",
            "drink": "sprite",
            "content": "Lorem ipsum dolor sit amet"
        }
    },
    {
        "restaurant": {
            "name": "Dominos",
            "food": "pizza",
            "drink": "root beer",
            "content": "Lorem ipsum dolor sit amet"
        }
    },
    {
        "restaurant": {
            "name": "Popeyes",
            "food": "chicken",
            "drink": "mist",
            "content": "Lorem ipsum dolor sit amet"
        }
    }
  ];

var $food = $('#food'),
    $drink = $('#drink'),
    $result = $('#result');

$food.change(function () {
    onChange();
});

$drink.change(function () {
    onChange();
});

function onChange() {
    var findedRestaurants = findRestaurants();
    showRestaurants(findedRestaurants);
}

function findRestaurants() {
    return filter($food.find('option:selected').val(), $drink.find('option:selected').val());
}

function filter(food, drink) {
    var result = [];

    for (var i = 0; i < restaurants.length; i++) {
        var restaurant = restaurants[i].restaurant;
        if ((!food || restaurant.food === food) && (!drink || restaurant.drink === drink)) {
            result.push(restaurant);
        }
    }

    return result;
}

function showRestaurants(restaurants) {
    $result.empty();
    for (var i = 0; i < restaurants.length; i++) {
        $result.append($('<li>' + restaurants[i].name + '</li>'));
    }
}

onChange();