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

210
Visualizações
Shorthand syntax to push or create item to array, at certain key of object

I have an object of the following type:

type ObjectOfArrays = {
    [id: string]: Array<string>
};

At multiple places in my code I want to push strings to the correct array, referenced by the id. Currently, I would have to do this in the following way:

if (id in obj)
    obj[id].push("text");
else
    obj[id] = ["text"];

Is it possible to do this in a shorter way? I understand it probably won't be as simple as an object with numbers, like done here. However, I am curious if there are alternative notations.

Any suggestions or references are welcome, thanks.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can do something similar to the other answer, using an empty array as a default and concat:

const obj = {}

id = '4'
obj[id] = (obj[id] || []).concat(['test'])
console.log(obj)

obj[id] = (obj[id] || []).concat(['test2'])
console.log(obj)

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