skip to Main Content

I am trying to get specific keys of a certain value within an object into an array. When I specify the value the array is filled with all keys not just the ones that match the value. I only want the keys that have a value that matches my IF statement. If my value doesn’t match any of the values the array is empty, that works but if my value matches one f the keys then all keys are returned in the array, which is not what I want. I only want the key that matches the value of the key value pair.

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)

2

Answers


  1. you can use Object.entries to implement this logic.

    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)
    Login or Signup to reply.
  2. Hugo Fang’s example is good, but using a reduce will allow you to do the same process with only one loop through the array.

    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)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search