Angular中如何根据模糊输入获取对象中对应的键值对
Angular实现对象键值对的模糊匹配功能
给定示例对象:
const sampleObject = { "29": "DTE Queue", "30": "Services Reporting Sales", "31": "Services Reporting Ops", "41": "UPLOAD", "55": "Support Report" };
当用户输入'sup'时,期望输出{"55": "Support Report"}。你现有的精确匹配函数仅能返回完全匹配的单个键,要实现模糊匹配并返回所有符合条件的键值对,可以按以下方式修改:
修改后的模糊匹配函数
function getMatchingEntries(object: {[key: string]: string}, searchTerm: string): {[key: string]: string} { // 统一转小写,实现大小写不敏感的模糊匹配 const lowerCaseSearchTerm = searchTerm.toLowerCase(); // 遍历对象键值对,筛选符合条件的条目 return Object.entries(object).reduce((matchedEntries, [key, value]) => { if (value.toLowerCase().includes(lowerCaseSearchTerm)) { matchedEntries[key] = value; } return matchedEntries; }, {} as {[key: string]: string}); }
函数逻辑说明
- 使用
Object.entries()将对象转换为键值对数组,方便遍历处理 - 把搜索词和对象值统一转为小写,避免大小写差异导致匹配失败
- 通过
reduce()方法构建结果对象,将包含搜索词的键值对逐一加入 - 返回最终的匹配结果对象
示例用法
// 调用函数获取匹配结果 const result = getMatchingEntries(sampleObject, 'sup'); console.log(result); // 输出: {"55": "Support Report"}
扩展调整
- 如果需要区分大小写的模糊匹配,去掉所有
.toLowerCase()调用即可 - 如果需要匹配键而非值,将判断条件改为
key.toLowerCase().includes(lowerCaseSearchTerm)
内容的提问来源于stack exchange,提问作者DIMPLE PANDA
相关产品推荐
相关产品推荐

