• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: Shorthand syntax to push or create item to array, at certain key of object

Resolved: Shorthand syntax to push or create item to array, at certain key of object

0
By Isaac Tonny on 16/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

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.

Answer:

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)

If you have better answer, please add a comment about this, thank you!

javascript javascript-objects typescript
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: How to convert Java bytecode to Webassembly using CheerpJ compiler

24/03/2023

Resolved: Is pandas groupby() function always produce a DataFrame with the same order respect to the column we group by?

24/03/2023

Resolved: Kivy widget hierarchy not behaving as expected

24/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.