Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

71
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda