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

162
Vistas
How to retrieve object property but also set it if it's undefined, without repetition

TL;DR

How can I simplify this code so that the long property name store.user[userId].order[orderId].items is only specified once?

if (!store.user[userId].order[orderId].items) store.user[userId].order[orderId].items = new Set();
if (store.user[userId].order[orderId].items.has('apples')) store.user[userId].order[orderId].items.add('oranges');

Detail

I have a really long object property that makes the code difficult to read. I would like to use a variable as an alias to simplify the code, like this:

let items = store.user[userId].order[orderId].items;
if (items.has('apples')) items.add('oranges');

However if the property hasn't yet been set, I get errors. So I need to define a default object:

let items = store.user[userId].order[orderId].items || new Set();
if (items.has('apples')) items.add('oranges');

However while this works on an existing object, if the new Set() was called then I still need to put the new instance back into the lengthy object to persist it:

let items = store.user[userId].order[orderId].items || new Set();
if (!store.user[userId].order[orderId].items) store.user[userId].order[orderId].items = items;
if (items.has('apples')) items.add('oranges');

Which kind of defeats the purpose.

Is there a way I can use this variable as an alias for the longer property, while supplying and setting a default value if the property doesn't exist yet, but such that I only need to specify the long property name once?

While my example case here is a bit contrived, I encounter this situation a lot when I am looping through data. The same code runs on each iteration but as it encounters different incoming data, it needs to add to existing structures or create them if they don't exist yet - so creating all the properties up front isn't really an option, as you don't know which properties to create until you're in the middle of processing the data.

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

0

In case you're accessing an object that might be nested inside optional undefined, use this method.

To set a nullish coalescing (put a value if the variable null or undefined) use this:


    let a = bla.bla.mightByNullOrUndefined?.obj?.nested
    a ??= somethingElse

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