如何用TypeScript按指定规则过滤JSON数据?
解决先匹配Code再匹配Name的过滤逻辑问题
问题背景
你有一组城市数据的JSON数组:
const jsonList = [ {name:'chennai', code:'maa'}, {name:'delhi', code:'del'}, // ...其他城市数据 {name:'salem', code:'che'}, {name:'bengaluru',code:'blr'} ];
想要实现先匹配code字段,无匹配结果时再匹配name字段的过滤逻辑——比如输入CHE时,应该优先返回code为che的{name:'salem', code:'che'},只有当没有任何code匹配时,才去匹配name字段。但你之前写的两段filter代码都没达到预期,每次都会优先匹配name字段。
问题原因
你原来的代码用了逻辑或||,只要项满足code匹配或者name匹配就会被纳入结果,这就导致两种匹配结果会混在一起,没有优先级。比如输入che时,chennai的name包含che,salem的code是che,两个都会被筛选出来,而且没有区分优先级。
解决方案
我们需要把过滤逻辑拆成两步,先优先获取code匹配的结果,如果结果为空,再去获取name匹配的结果,这样就能保证优先级了。
修改后的TypeScript代码如下:
public filterJson(text: string) { const lowerText = text.toLowerCase(); // 第一步:筛选code匹配的项 const codeMatches = this.jsonList.filter(e => e.code.toLowerCase().includes(lowerText) ); // 如果code有匹配结果,就用这个;否则再筛选name匹配的 const finalMatches = codeMatches.length > 0 ? codeMatches : this.jsonList.filter(e => e.name.toLowerCase().includes(lowerText) ); // 取前9个结果 this.filteredOptions = finalMatches.slice(0, 9); }
如果你的需求是前缀匹配(比如输入che只匹配code以che开头的,而不是包含的),就把includes换成startsWith:
public filterJson(text: string) { const lowerText = text.toLowerCase(); const codeMatches = this.jsonList.filter(e => e.code.toLowerCase().startsWith(lowerText) ); const finalMatches = codeMatches.length > 0 ? codeMatches : this.jsonList.filter(e => e.name.toLowerCase().startsWith(lowerText) ); this.filteredOptions = finalMatches.slice(0, 9); }
逻辑说明
- 先把输入文本转成小写,避免大小写敏感的问题
- 先过滤出所有code匹配的项,优先使用这个结果
- 只有当code匹配结果为空时,才去过滤name匹配的项
- 最后统一截取前9个结果,符合你原来的需求
这样就能完美实现“先code后name”的优先级过滤啦!
内容的提问来源于stack exchange,提问作者Munna Babu
相关产品推荐
相关产品推荐

