Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

213
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!