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

如何搜索对象的键获取匹配值,且按键的匹配度高低对结果排序

普通对象搜索功能实现方案

基础功能实现(无排序)

实现逻辑

  • 将搜索关键词和对象所有键统一转为小写,实现不区分大小写的匹配
  • 遍历对象键,筛选出包含关键词的键,收集对应值返回

代码实现

function basicSearch(obj, keyword) {
  const lowerKeyword = keyword.toLowerCase();
  const result = [];
  for (const key in obj) {
    if (key.toLowerCase().includes(lowerKeyword)) {
      result.push(obj[key]);
    }
  }
  return result;
}

测试用例

const testObj1 = {
  onE:"two",
  three:"four",
  wOn:"too"
};
console.log(basicSearch(testObj1, "ON")); // 输出 ["two", "too"]

进阶功能实现(带匹配度排序)

匹配度排序规则(符合示例要求)

  1. 第一优先级:关键词在键中出现的次数,次数越高排名越靠前
  2. 第二优先级:相同出现次数下,键的长度越短排名越靠前(更短的键匹配集中度更高)

代码实现

function advancedSearch(obj, keyword) {
  const lowerKeyword = keyword.toLowerCase();
  // 先筛选匹配的键并计算匹配度参数
  const matchedItems = [];
  for (const key in obj) {
    const lowerKey = key.toLowerCase();
    if (lowerKey.includes(lowerKeyword)) {
      // 计算关键词出现次数
      const matchCount = lowerKey.split(lowerKeyword).length - 1;
      matchedItems.push({
        value: obj[key],
        matchCount: matchCount,
        keyLength: key.length
      });
    }
  }
  // 按规则排序
  matchedItems.sort((a, b) => {
    // 先按匹配次数降序
    if (b.matchCount !== a.matchCount) {
      return b.matchCount - a.matchCount;
    }
    // 次数相同按键长度升序
    return a.keyLength - b.keyLength;
  });
  // 提取值返回
  return matchedItems.map(item => item.value);
}

测试用例

const testObj2 = {
  "one one zero":"0",
  "zero":"1",
  "one two":"2",
  "one one":"3"
};
console.log(advancedSearch(testObj2, "one")); // 输出 ["3", "0", "2"]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 19:18:03