You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 23:45:03