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
you can use
Object.entries
to implement this logic.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.