0

I want to know if there is a clean way to modify a value in a hashmap or create it if it doesn't exist without doing an if block. Example of what i'm currently doing

let dict = {}
if(dict['key']){
 dict['key'] += 1
} else {
 dict['key'] = 1
}

Want to know if there is a cleaner way to do what I did above.

xeroshogun
  • 1,062
  • 1
  • 18
  • 31
  • You could use the ternary operator ... – Siddharth Seth Feb 12 '22 at 17:12
  • Does this answer your question? [How to increment an object property value if it exists, else set the initial value?](https://stackoverflow.com/questions/18690814/how-to-increment-an-object-property-value-if-it-exists-else-set-the-initial-val) – Ivar Feb 12 '22 at 17:16
  • Does this answer your question? [How to increment a value in a JavaScript object?](https://stackoverflow.com/questions/39590858/how-to-increment-a-value-in-a-javascript-object) – pilchard Feb 12 '22 at 17:17

1 Answers1

0

Use dot notation, because the property isn't dynamic, and alternate dict.key with 0 before adding 1.

dict.key = (dict.key || 0) + 1;
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320