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

70
Vistas
Condition Spread based on Object props

I'm looking for way to remove empty or null props, on my example obj2, I want to avoid copying the birthPlace property or any other prop that comes empty.

const obj1 = { firstName: 'Foo', age: 22 };

const obj2 = { lastName: 'Bar', gender: 'M', birthPlace: '' };

const newObj = { ...obj1, ...obj2 };

Desired result:

{firstName: 'Foo', age: 22, lastName: 'Bar', gender: 'M'}

Is it possible using Conditional Objects props using Spread Operators in javascript?

const updateUserObj = {
  ...(obj1 !== check here<hasPropEmpty> && obj2)
}
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

There's no shorthand for it, but you can easily write a function that filters out those properties.

function nonEmptyProps(obj) {
  return Object.fromEntries(Object.entries(obj).filter(([k, v]) => v !== null && v !== ''));
}

const obj1 = { firstName: 'Foo', age: 22 };

const obj2 = { lastName: 'Bar', gender: 'M', birthPlace: '' };

const newObj = {...nonEmptyProps(obj1), ...nonEmptyProps(obj2)};
console.log(newObj);

about 4 years ago · Juan Pablo Isaza Denunciar

0

Using Object#entries you get the key-value pairs of an object, then, using Array#filter you iterate over these pairs to filter out the ones with empty values. Then, using Object#fromEntries you construct back the resulting pairs to an object.

const filterProps = (obj = {}) => 
  Object.fromEntries(
    Object.entries(obj).filter(([key, value]) => 
      value !== null && value !== undefined && value !== ''
    )
  );

const obj1 = { firstName: 'Foo', age: 22 };
const obj2 = { lastName: 'Bar', gender: 'M', birthPlace: '' };

const newObj = { ...filterProps(obj1), ...filterProps(obj2) };

console.log(newObj);

about 4 years ago · Juan Pablo Isaza 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