[英]Javascript :Dynamic expression in filter function based on variable values
我正在尝试使用lodash.js
基于某些参数实现用于显示总线列表的过滤功能。
这是用于过滤boardingPoint,droppingPoint,busType和operatorName的四个参数,它将填充在四个下拉菜单中。
工作流程
当用户选择一个登机点时,结果应仅包含具有选定登机点的公交车列表,
如果他选择boardingPoint和droppingPoint,则结果应仅包含选择了boradingPoint和dropping Points的公交车列表。
这是我的过滤功能
function search_buses(bpLocations,dpLocations,busTypes,operatorNames){
//filter function
tresult = _.filter(result, function(obj) {
return _(obj.boardingPoints).map('location').intersection(bpLocations).value().length > 0
&&_(obj.droppingPoints).map('location').intersection(dpLocations).value().length > 0
&& _.includes(busTypes, obj.busType)
&& _.includes(operatorNames, obj.operatorName);
});
//return result array
return tresult;
}
但是问题在于,如果用户仅选择两个条目,例如登机点和落点,而其他条目为空,则上述筛选条件失败,因为它将评估四个条件。 仅当所有4个参数均具有任何值时,以上方法才有效。
所以我该如何修改上面的表达式,它应该只包含选定的过滤参数
例如:如果用户选择登机点和落点(即bpLocations
, dpLocations
),则仅此表达式
tresult = _.filter(result, function(obj) {
return _(obj.boardingPoints).map('location').intersection(bpLocations).value().length > 0
&&_(obj.droppingPoints).map('location').intersection(dpLocations).value().length > 0
});
如果仅选择busType,则应为
tresult = _.filter(result, function(obj) {
return _.includes(busTypes, obj.busType)
});
更新
我只是串联基于每个变量的表达式字符串是否为空
//expression string
var finalvar;
tresult = _.filter(result, function(obj) {
if(bpLocations!=''){
finalvar+=_(obj.boardingPoints).map('location').intersection(bpLocations).value().length > 0;
}
if(dpLocations!=''){
finalvar+=&&+_(obj.droppingPoints).map('location').intersection(dpLocations).value().length > 0;
}
if(busTypes!=''){
finalvar+=&&+ _.includes(busTypes, obj.busType);
}
if(operatorNames!=''){
finalvar+=&&+ _.includes(operatorNames, obj.operatorName);
}
return finalvar;
});
但是它将返回此错误Uncaught SyntaxError: Unexpected token &&
首先,需要对finalvar进行初始化。 如果在没有选择任何内容的情况下根本不需要过滤器(我假设这是您想要的逻辑),则应将其初始化为true。
其次,在这种情况下,加法分配“ + =”使用不正确。 请在这里检查正确的用法。
第三,&&是JavaScript运算符,不能将其添加到另一个值中。 这就是为什么您得到错误。
这是修改后的代码,可以解决问题和预期的逻辑:
// initialize to true means no filter if nothing is selected (return the item).
var finalvar = true;
var tresult = _.filter(result, function(obj) {
if(bpLocations){
finalvar = finalvar && _(obj.boardingPoints).map('location').intersection(bpLocations).value().length > 0;
}
if(dpLocations){
finalvar = finalvar && _(obj.droppingPoints).map('location').intersection(dpLocations).value().length > 0;
}
if(busTypes){
finalvar = finalvar && _.includes(busTypes, obj.busType);
}
if(operatorNames){
finalvar = finalvar && _.includes(operatorNames, obj.operatorName);
}
return finalvar;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.