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

213
Vistas
javascript spread operator decision making

myfunction takes object of a persons as input and returns an a new object contaning first name, last name size and weight of person. If either weight or size was not gven in input object it should not be present in output object

function myFunction(obj) {
  return {
    fn: obj.fn,
    ln: obj.ln,
    ...(obj.size && { size: `${obj.size}cm` }),
    ...(obj.weight && { weight: `${obj.weight}kg` }),
  };
}
myFunction({ fn: 'Lisa', ln: 'Müller', age: 17, size: 175, weight: 67 })

I can't understand how ...(obj.size && { size:${obj.size}cm}), works

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can conditionally create objects with the values (if present), or empty objects (if not present), then (unconditionally) spread them in to the resulting object:

function myFunction(obj) {
  const size = obj.size ? { size: `${obj.size}cm` } : {};
  const weight = obj.weight ? { weight: `${obj.weight}kg` } : {};
  const {fn, ln} = obj;
  return {fn, ln, ...size, ...weight};
}

Alternatively (and perhaps a bit less complicated), you can create the result object first, then conditionally set the property values:

function myFunction(obj) {
  const {fn, ln} = obj;
  const result = {fn, ln};
  if (obj.size) result.size = `${obj.size}cm`;
  if (obj.weight) result.weight = `${obj.weight}kg`;
  return result;
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

This works because of "short circuit evaluation" with the && operator.

If the first operand is falsey, nothing will be "spread" into the object literal. If it is not falsey the object { size: ${obj.size}cm } will be spread into the returned object literal.

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