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

161
Visualizações
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 Respostas
Responde à pergunta

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