You need to enable JavaScript to run this app. JavaScript实现按对象值匹配返回对应键的搜索提示功能开发
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript实现按对象值匹配返回对应键的搜索提示功能开发

可落地实现方案

核心匹配规则对齐

为了完全匹配你给出的测试预期,实现逻辑严格遵循以下规则:

  • 匹配为大小写不敏感的子串包含模式,适配实际搜索场景的输入容错
  • 返回的键顺序严格对齐数据对象中属性键的原生出现顺序,不打乱原有结构顺序
  • 仅保留存在至少一个匹配值的属性键,无匹配的键直接剔除
  • 增加类型判断兜底,避免非字符串类型的属性值触发匹配报错

函数实现代码

function getKeysInMatchesInValue(arr, searchValue) {
  // 统一转换为小写做不敏感匹配
  const lowerSearch = searchValue.toLowerCase();

  // 1. 按原生顺序收集所有出现过的不重复属性键
  const allKeys = [];
  const keyRecorder = new Set();
  arr.forEach(item => {
    Object.keys(item).forEach(key => {
      if (!keyRecorder.has(key)) {
        keyRecorder.add(key);
        allKeys.push(key);
      }
    })
  })

  // 2. 逐键检查是否存在匹配的属性值
  const matchedKeys = [];
  allKeys.forEach(key => {
    const hasMatch = arr.some(item => {
      const value = item[key];
      // 仅对字符串值执行匹配判断
      if (typeof value !== 'string') return false;
      return value.toLowerCase().includes(lowerSearch);
    })
    if (hasMatch) matchedKeys.push(key);
  })

  return matchedKeys;
}

测试用例验证

使用你提供的示例数组调用函数,输出结果与预期完全一致:

  • 调用getKeysInMatchesInValue(arr, 'Ma') → 输出['name', 'gender']
  • 调用getKeysInMatchesInValue(arr, 'Fe') → 输出['name', 'gender']
  • 调用getKeysInMatchesInValue(arr, 'Fer') → 输出['name']
  • 调用getKeysInMatchesInValue(arr, 'Ber') → 输出['name']
  • 调用getKeysInMatchesInValue(arr, 'Ac') → 输出['name', 'status']

可调整配置点

  • 如果需要严格大小写匹配,直接移除代码中toLowerCase()的转换逻辑即可
  • 如果需要前缀匹配(而非任意位置子串匹配),可以将includes方法替换为对值开头位置的判断,比如value.toLowerCase().startsWith(lowerSearch)

内容的提问来源于stack exchange,提问作者Jakegarbo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.28 22:36:06