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

遍历对象提取特定值对应键至数组的代码问题排查

问题修复:提取对象中值匹配的键

你的代码核心错误是:当匹配到值为36的键值对时,你向数组推入了整个chestSize对象,而非当前循环的key变量。以下是修正方案:

修正后的for...in写法

const chestSize = {
  "Leanne": 30,
  "Denise": 26,
  "Carol": 36,
  "Jill": 28,
  "Randy": 32
};

const chestSizeThirtySix = []

for (const key in chestSize) {
  if (chestSize[key] === 36) {
    chestSizeThirtySix.push(key) // 将整个对象替换为当前键
  }
};
console.log(chestSizeThirtySix) // 输出: ["Carol"]

更简洁的现代JS写法

如果想让代码更简洁,可以用Object.keys结合filter,直接过滤出符合条件的键:

const chestSize = {
  "Leanne": 30,
  "Denise": 26,
  "Carol": 36,
  "Jill": 28,
  "Randy": 32
};

const chestSizeThirtySix = Object.keys(chestSize).filter(key => chestSize[key] === 36);
console.log(chestSizeThirtySix) // 输出: ["Carol"]

或者用Object.entries先转换为键值对数组,过滤后提取键:

const chestSize = {
  "Leanne": 30,
  "Denise": 26,
  "Carol": 36,
  "Jill": 28,
  "Randy": 32
};

const chestSizeThirtySix = Object.entries(chestSize)
  .filter(([_, value]) => value === 36)
  .map(([key]) => key);
console.log(chestSizeThirtySix) // 输出: ["Carol"]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 11:56:03