You're flipping what property you're accessing. You got it right the first time, but not the second:
function removeNumbersLargerThan(num, obj) {
for(var key in obj){
if(obj[key] > num){ // Correct!
delete obj.key; // Should be obj[key] again
}
}
return obj;
}
Otherwise you're going to delete the "key" property off of the obj
In other words, your loop isn't delete
ing the property you actually want to delete
. It's just delete
ing the key
property on an Object:
// What you declare
let num = 5;
let obj = {
key: "hello",
keyToKill: 7,
keyToLeaveAlone: 3
}
// Your initial loop to remove keys with value greater than a number
for (let key in obj) {
// If I find a key whose value is greater than num
if (obj[key] > num) {
// Delete the "key" property
delete obj.key;
}
}
// The above will give you this:
let incorrect = {
keyToKill: 7,
keyToLeaveAlone: 3
}
If you want to delete the property whose value is greater than num
you would do the following:
// If you do the following instead:
for (let key in obj) {
// If I find a key whose value is greater than num
if (obj[key] > num) {
// Delete the property who's value is greater than num
delete obj[key];
}
}
// You'll get this
let correct = {
key: "hello",
keyToLeaveAlone: 3
}