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

127
Visualizações
is it possible to make spread operator ignore undefined propperties

Given the following

[{ a: 5, b: 2 }, { a: 2, b: 5 }].map(x => {
  return {
    ...x,
    b: undefined
  }
})

I would like to end up with something like

[{a:5},{a:2})

Is that possible? I know I could do something like

[{ a: 5, b: 2 }, { a: 2, b: 5 }].map(x => {
const obj = {
    ...x,
  }
  delete obj.b
  return obj
})

or

[{ a: 5, b: 2 }, { a: 2, b: 5 }].map(x => {
  return {
    a: x.a
  }
})

The first method results in the values just being set to "undefined". The second method seems wasteful for larger arrays as a new variable is created object, and also my typescript complains about it because the original property wasn't optional. The third method works if you only want to retain a small number of properties, but once it gets over just a few properties it just seems unwieldy. For my current case, I'll probably opt for the second method, but I am curious if there's a way to handle this more elegantly.

I'm aware that I can also do something like:

Object.keys(obj).forEach(key => obj[key] === undefined && delete obj[key])

But it still doesn't seem all that elegant.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can just ignore the b and collect all properties in rest and then spread the rest in the final result.

You can also make it one liner

const result = arr.map(({ b, ...rest }) => rest);

const arr = [
  { a: 5, b: 2 },
  { a: 2, b: 5 },
]
const result = arr.map(({ b, ...rest }) => rest);

console.log(result);

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