我正在尝试使用 input[type="range"]
元素过滤 JSON 数据。我已经达到了过滤器可以工作但不能完美工作的程度。
假设默认的filters
对象如下所示:
filters = {
price: 100,
rating: 3,
beds: 1,
people: 1
}
使用这个概念,并在input
事件上更改filters
的值,公寓会被非常严格地过滤,同时考虑到默认值和用户实际想要的值进行过滤。
apartments = apartments.filter(apartment => {
if (typeof apartment.price == 'string') {
apartment.price = apartment.price.replace( /^\D+/g, '');
}
if (apartment.price <= (filters.price - 100) ||
apartment.price >= filters.price) {
return false;
}
if (apartment.rating != filters.rating)
return false;
if (apartment.beds != filters.beds)
return false;
if (apartment.people != filters.people)
return false;
else
return true;
});
这里的问题是:
如何通过仅考虑用户更改的过滤器的值来使过滤器变得更好?
我尝试简单地删除默认值,但在这种情况下,过滤器永远不会匹配,因为值不存在,并且通过设置默认值,即使用户只更改了所有 4 个值,公寓也会被严格过滤其中之一。
以下是过滤器在我的应用程序上的外观: http://prntscr.com/e6h3oq
这是用 JSON 表示的一套公寓:
{
"id":1,
"title":"ultrices posuere cubilia curae",
"description":"Suspendisse potenti. In eleifend quam a odio. In hac habitasse platea dictumst.\n\nMaecenas ut massa quis augue luctus tincidunt. Nulla mollis molestie lorem. Quisque ut erat.",
"date":"3/9/2016",
"price":"£200.32",
"rating":2,
"address":"7 Harbort Drive",
"beds":2,
"people":2,
"user":{
"first_name":"Douglas",
"last_name":"Hansen",
"email":"dhansen0@skype.com",
"phone":"66-(363)851-6428"
}
}
您只需检查过滤器对象中是否设置了属性。如果它是未定义
,则从过滤器返回true
。
我会稍微重构一下你的代码:
您对床位、人员和评级的检查非常相似,因此我会将其移至柯里化(Currying)函数,如下所示:
const propertyFilter = (propertyName) => {
return (appartment) => {
if(filters[propertyName] != undefined) {
return filters[propertyName]== apartment[propertyName]);
}
return true;
}
}
您还可以引入函数来处理价格解析逻辑,并避免将其与过滤代码混合。
const parsePrice = (price) => {
if (typeof price == 'string') {
price = price.replace( /^\D+/g, '');
}
return price;
}
然后你可以像这样使用它:
apartments
.filter(propertyFilter("people"))
.filter(propertyFilter("beds"))
.filter(propertyFilter("rating"))
.filter(apartment => {
if(apartment.price != undefined) {
const price = parsePrice(apartment.price);
if (price <= (filters.price - 100) || price >= filters.price) {
return false;
}
}
return true;
})
我是一名优秀的程序员,十分优秀!