Skip to main content

Command Palette

Search for a command to run...

JS: Eliminar valores undefined,null,false y '' de un objeto

Published
1 min read
JS: Eliminar valores undefined,null,false y '' de un objeto
N

🤓 Passionate about technology and problem-solving, with experience in developing scalable solutions.

💪🏻 I love working in collaborative teams, contributing ideas, learning new things and contribute to projects that make a real difference!

🚀 I'm driven by innovation and continuously seek out new challenges that allow me to create impactful solutions

Si tenes el siguiente objeto:

const obj = {
    val1: 'val1', 
    val2: null, 
    val3: '', 
    val4: 'val4',
    val5: false;
}

Y deseamos remover los valores false, undefined, null y también los valores vacíos (string vacío '') para obtener el siguiente objeto:

const obj = {
    val1: 'val1', 
    val4: 'val4'
}

Solución

Todo lo que tenemos que hacer es recorrer el objeto y eliminar esos valores con lo siguiente:

Object.fromEntries(Object.entries(obj).filter(value => value[1]));

Eso devolverá un nuevo objeto sin alterar el nuestro, entonces podríamos guardarlo en una nueva constante:

const newObj = Object.entries(obj).filter(value => value[1])

Y ahora newObj contiene nuestro nuevo objeto sin valores vacíos, nulos, undefined ni false!