【发布时间】:2021-08-24 22:01:28
【问题描述】:
我需要按多个条件过滤酒店:星级(多选)、类型(多选)、价格(两端的范围)、国家/地区(列表之一)。我试着这样做:
document.getElementById("app").innerHTML =`${hotels.filter(star => star.stars === 4).filter(type => type.type === "hostel").map(hotelTemplate)}`
但我发现我只能应用一种方法filter 和map。有人知道是否有办法应用多个filter 方法,然后map 它们?
如果您需要更多详细信息,请附上完整代码:
async function filters(){
const requestUrl = "js/hotels.json";
const response = await fetch(requestUrl);
const data = await response.json();
const hotels = Object.values(data.hotels);
const hotelTemplate = (hotel) => {
return `
<div class="result">
<img class="result__img" src="images/hotel2.png" alt="${hotel.name}">
<div class="result__description">
<p class="result__address">${hotel.address}</p>
<h3 class="result__name">${hotel.name}</h3>
<div class="result__details">
<div class="rating">
<div class="rating__stars">${hotel.stars}</div>
<p class="rating__words"></p>
</div>
<div class="result__type">${hotel.type}</div>
</div>
<p class="result__info">${hotel.description}</p>
</div>
<div class="result__cta">
<div class="review">
<div class="review__head">
<div class="review__rating">
<img class="review__star" src="images/star.svg" alt="${hotel.name}">
<p class="review__rate">${hotel.rating}</p>
</div>
<p class="review__estimate">Good</p>
<p class="review__amount"><span class="review__number">${hotel.reviews_amount}</span> reviews</p>
</div>
<div class="review__body">
<p class="review__text">"${hotel.last_review}"</p>
</div>
</div>
<div class="order">
<div class="order__price">
<p class="order__offer">от <span class="order__amount">${eurFormatter.format(parseInt(hotel.min_price))}</span></p>
</div>
<button class="order__book">
Book now
</button>
</div>
</div>
</div>
`;
}
document.getElementById("app").innerHTML =`${hotels.filter(star => star.stars === 4).map(hotelTemplate)}`
【问题讨论】:
-
您的代码似乎可以工作。将过滤器链接到地图中应该没问题
-
@Kinglish,你好!感谢你的回复!有时它确实有效,但当我需要链接星星时。假设用户选择查看 3 星、4 星和 5 星的酒店。所以如果我这样做:
document.getElementById("app").innerHTML =${hotels.filter(star => star.stars === 5).filter(star => star.stars === 5).map(hotelTemplate)}代码没有正确执行,它也不会返回任何错误:(
标签: javascript arrays json filter mapping