0

Is there a way to loop over an object and remove properties where the value matches a certain condition? In this case, I want to remove any properties that have no value.

Here is what I have:

var user = { first : 'John', last : 'Doe', city : 'Boston', state : 'MA', zip : '', birthdate : ''}

for(const [key, value] of Object.entries(user)){
  if(!value){
    delete user.key;
   }
 });

The code is detecting an empty value, but the delete function is not working;

Thanks!

Caldera500
  • 97
  • 10

2 Answers2

0

Reflect.deleteProperty(user, key);

you can use something like this

Siva K V
  • 9,737
  • 2
  • 13
  • 29
0

You were almost there, try like so:

var user = { first : 'John', last : 'Doe', city : 'Boston', state : 'MA', zip : '', birthdate : ''};

for (let [key, value] of Object.entries(user)) {
  if(value.length <= 0) {
      delete user[key]
  }
}
console.log(user);
caramba
  • 21,282
  • 18
  • 84
  • 125