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

209
Vistas
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 Respuestas
Responde la pregunta

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