迭代一个对象并将特定值的任何键传递给数组

问题描述 投票:0回答:2

我试图将对象中某个值的特定键放入数组中。当我指定值时,数组将填充所有键,而不仅仅是与该值匹配的键。我只想要具有与我的 IF 语句匹配的值的键。如果我的值与任何值都不匹配,则数组为空,这是可行的,但如果我的值与键之一匹配,则所有键都将返回到数组中,这不是我想要的。我只想要与键值对的值匹配的键。

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(chestSize)
  }
};
console.log(chestSizeThirtySix)

javascript for-loop if-statement conditional-statements javascript-objects
2个回答
1
投票

你可以使用

Object.entries
来实现这个逻辑。

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

const chestSizeThirtySix = Object.entries(chestSize)
  .filter(([key, value]) => value === 36)
  .map(([key, value]) => ({[key]:value}))
 
console.log(chestSizeThirtySix)


1
投票

Hugo Fang 的示例很好,但是使用reduce 将允许您仅通过数组进行一次循环即可完成相同的过程。

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

const chestSizeThirtySix = Object.entries(chestSize)
  .reduce((r,[key,value]) => [...r, ...value === 36 ? [{[key]:value}] : []], [])

console.log(chestSizeThirtySix)

© www.soinside.com 2019 - 2024. All rights reserved.