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

128
Vistas
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 Respuestas
Responde la pregunta

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