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

JavaScript中如何获取对象中值为指定值的所有键

解决方案

你当前使用的Array.prototype.find()方法本身仅会返回数组中第一个满足判定条件的元素,因此只能得到第一个匹配的键。如果需要获取所有匹配指定值的键,将find替换为Array.prototype.filter()即可,该方法会返回所有满足判定条件的元素组成的数组。

改进后的实现代码如下:

function getKeysByValue(object, value) {
  return Object.keys(object).filter((key) => object[key] === value);
}

针对你的示例场景的调用方式:

const issues = {
  window_expired: 'Yes',
  no_power: 'No',
  no_display: 'Yes'
};

const result = getKeysByValue(issues, 'Yes');
// 得到的result为 ["window_expired", "no_display"],符合预期需求

内容的提问来源于stack exchange,提问作者Some dude on the internet

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 02:54:06