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
相关产品推荐
相关产品推荐

