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

138
Vistas
Syntax for bracket-notation-property-accessors to conditionally access the entire object rather than a given property

Suppose I have the following:

const myFunction = ({ returnProp = null }) => ({
    propA: 'val1',
    propB: 'val2',
    propC: 'val3'
})[returnProp || {}]
//               ^^
//               not sure what to put here

If returnProp is null, how can I return the whole object?

If I specify returnProp, I would like it returned:

const propA = myFunction({ returnProp: 'propA' }) // 'val1'

If I do not specify it, I'd like the whole object:

const obj = myFunction({})
/*
    {
        propA: 'val1',
        propB: 'val2',
        propC: 'val3'
    }
*/
about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You can achieve it using nullish coalescing operator.

const myFunction = ({ returnProp = null }) => {
  const obj = {
    propA: "val1",
    propB: "val2",
    propC: "val3",
  };
  return obj[returnProp] ?? obj;
};

console.log(myFunction({ returnProp: "propA" }));
console.log(myFunction({ returnProp: null }));
console.log(myFunction({ returnProp: undefined }));
console.log(myFunction({}));

about 4 years ago · Juan Pablo Isaza Denunciar

0

Could maybe use a getter invoked with an empty string:

const myFunction = ({ returnProp = '' }) => ({
    propA: 'val1',
    propB: 'val2',
    propC: 'val3',
    get ['']() {delete this['']; return this}
})[returnProp]


console.log(myFunction({ returnProp: "propA" }));
console.log(myFunction({}));

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