Skip to content
Advertisement

Remove empty values from array of objects only if the value is empty in all objects

I’m trying to remove the empty strings in my array.

This is my array:

let array = [{name:'John',age:'18',address:''},{name:'George',age:'',address:''},{name:'Kevin',age:'25',address:''}]

I would like to remove the empty string values ONLY if it’s empty in all objects.

desired outcome:

[{name:'John',age:'18'},{name:'George',age:''},{name:'Kevin',age:'25'}]

This is what I did but it removes EVERY empty string values:

 for (let i = 0; i < array.length; i++) {
 array[i] = Object.fromEntries(Object.entries(array[i]).filter(([_, v]) => v != ''));
 }

Thanks in advance ,

Advertisement

Answer

If you don’t mind mutating the original array object. Here’s a solution utilizing some array functions.

let array = [
  { name: 'John', age: '18', address: '' },
  { name: 'George', age: '', address: '' },
  { name: 'Kevin', age: '25', address: '' }
]

Object.keys(array[0])
  .filter(k => array.every(obj => !obj[k]))
  .forEach(k => array.forEach(obj => delete obj[k]));

console.log(array);
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement