Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

161
Vistas
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 ,

about 4 years ago · Santiago Gelvez
3 Respuestas
Responde la pregunta

0

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);

about 4 years ago · Santiago Gelvez Denunciar

0

You can solve this issue with a filter method

  • get all the entries to be scanned in the array;
  • for each entry, filter the array with it; if the output array is empty then you can delete this value in the original array

    let array = [{name:'John',age:'18',address:''},{name:'George',age:'',address:''},{name:'Kevin',age:'25',address:''}]
    
    const entries = Object.keys(array[0])
    
    entries.forEach(e => {
        if(array.filter(i => i[e]).length === 0) {
          array = array.map(i => {delete i[e]; return i})
        }
    })
    
    console.log(array)

about 4 years ago · Santiago Gelvez Denunciar

0

If you don't want to mutate the original array:

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


let result;

Object.keys(array[0])
.forEach(key => {
    if(array.every(e => e[key] === ''))
        result = array.map(({[key]:_,...rest}) => ({...rest}))
})

console.log(result)

about 4 years ago · Santiago Gelvez Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda