我不知道如何筛选具有多个条件的数组。我有一个带有2个select,1个复选框字段集和1个单选按钮字段集的搜索过滤器表单。我具有返回符合所选条件的项目的函数。它们只能单独工作。查找符合所有条件的对象的最佳方法是什么?

我试图为所有可能的选项制作if语句,但是代码无法正常工作,并且看来应该有一些更好的选择。

这是函数示例:

    function chooseRating(hotel) {
      return hotel.rating == e.target.value;
    }

    function chooseMeal(hotel) {
      return hotel.mealType == e.target.value;
    }


    function choosePlace(hotel)  {
      for (let l = 0; l < chosenPlace.length; l++) {
      if(chosenPlace[l].checked) {
        return hotel.region == e.target.value;
      }
              }
    }


我该如何过滤该数组?

  let filteredCards = hotels.filter(function(hotel, index, hotels) {
    // ??
  });


javascript - 具有多个条件的数组过滤javascript-LMLPHP

用户选择他对酒店的要求,他应该获得符合所有要求的酒店。而且,如果其中一些未选择,则默认情况下不计入它们。

最佳答案

您可以像这样链接filter()调用:

// first filter
function filterRating(hotel) {
  return hotel.rating >= filters.rating;
}

// second filter
function filterMeal(hotel) {
  return !filters.mealType.length || hotel.mealType == filters.mealType;
}

// apply both filters to initial array
function update() {
  let filteredCards = hotels.filter(filterRating).filter(filterMeal);
};

完整示例:

var filters = {
  rating: 4,
  mealType: ""
};

rating.value = filters.rating;
mealtype.value = filters.mealType;

rating.addEventListener("input", function() {
  filters.rating = rating.value;
  update();
});
mealtype.addEventListener("input", function() {
  filters.mealType = mealtype.value;
  update();
});

function filterRating(hotel) {
  return hotel.rating >= filters.rating;
}

function filterMeal(hotel) {
  return !filters.mealType.length || hotel.mealType == filters.mealType;
}

function update() {
  let filteredCards = getHotels().filter(filterRating).filter(filterMeal);
  console.log(filters);
  output.innerHTML = filteredCards.map(hotel => `<span>${hotel.name}</span>`).join("");
};
update();

function getHotels() {
  return [{
      name: "A",
      rating: 5,
      mealType: "full"
    },
    {
      name: "B",
      rating: 4,
      mealType: "full"
    },
    {
      name: "C",
      rating: 4,
      mealType: "breakfast"
    },
    {
      name: "D",
      rating: 5,
      mealType: "breakfast"
    }
  ];
}
input,
select {
  margin: 1em 0
}

#rating {
  width: 3em
}

#output span {
  display: inline-block;
  border: 1px solid black;
  padding: 0.5em;
  margin: 0.5em;
}
Rating &gt;= <input id="rating" value="5" type="number"><br> Meal:
<select id="mealtype">
  <option value="">any</option>
  <option>breakfast</option>
  <option>full</option>
</select><br>
<p id="output"></p>

关于javascript - 具有多个条件的数组过滤javascript,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52520048/

10-16 16:42