Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 ,

>Solution :

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading