Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any suggestions or references are welcome, thanks.

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading