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

如何在JavaScript的Map对象中根据值获取对应的键?

根据值获取Map对应的键

针对你现有的Map实例,不需要创建额外集合的话,可以直接遍历Map的键值对来匹配目标值:

情况1:值唯一(返回单个键)

const dict = new Map([
   ['a', '1'],
   ['b', '2']
]);

function getKeyByValue(map, targetValue) {
  for (const [key, value] of map.entries()) {
    if (value === targetValue) {
      return key;
    }
  }
  return undefined; // 没找到匹配值时返回undefined
}

// 使用示例
console.log(getKeyByValue(dict, '1')); // 输出 'a'
console.log(getKeyByValue(dict, '3')); // 输出 undefined

情况2:值不唯一(返回所有匹配的键)

如果你的Map中存在多个键对应同一个值,可以返回包含所有匹配键的数组:

function getKeysByValue(map, targetValue) {
  const matchedKeys = [];
  for (const [key, value] of map.entries()) {
    if (value === targetValue) {
      matchedKeys.push(key);
    }
  }
  return matchedKeys;
}

// 含重复值的示例场景
const dictWithDuplicates = new Map([
   ['a', '1'],
   ['b', '2'],
   ['c', '1']
]);
console.log(getKeysByValue(dictWithDuplicates, '1')); // 输出 ['a', 'c']

补充说明

这种方式直接遍历原Map完成匹配,无需额外创建反向映射集合。如果需要频繁根据值查询键,创建反向集合会更高效;但如果只是偶尔查询,直接遍历的开销完全可以忽略。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 17:38:26