JavaScript实现多条件过滤 匹配titel或sendFrom字段值
问题原因
你之前的代码不符合预期是因为逻辑或运算符||的短路执行逻辑:你写的判断只会优先取存在的titel字段转大写后做匹配,完全不会校验sendFrom字段是否符合匹配条件,自然达不到「两个字段任意一个匹配就返回」的需求。
修复后的实现代码
const newData = masterDataSource.filter(function (item) { const textData = text.toUpperCase(); // 单独处理两个字段,空值转为空字符串避免调用toUpperCase报错 const titleVal = item.titel ? item.titel.toUpperCase() : ''; const sendFromVal = item.sendFrom ? item.sendFrom.toUpperCase() : ''; // 任意一个字段包含搜索文本就返回true,保留当前条目 return titleVal.indexOf(textData) > -1 || sendFromVal.indexOf(textData) > -1; });
ES6+ 简化写法(可选)
如果你的运行环境支持ES6+语法,可以用可选链和includes方法简化代码:
const upperSearchText = text.toUpperCase(); const newData = masterDataSource.filter(item => (item.titel?.toUpperCase() || '').includes(upperSearchText) || (item.sendFrom?.toUpperCase() || '').includes(upperSearchText) );
以上逻辑会分别校验两个字段的匹配情况,只要其中一个满足搜索条件就保留对应条目,完全符合你的需求。
内容的提问来源于stack exchange,提问作者Brydawg
相关产品推荐
相关产品推荐

