Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to increment an object property value if it exists, else set the initial value?

Tags:

javascript

How might I add check to see if a key already exists, and if does, increment the value, and if it doesn't exist, then set the initial value?

Something like this pseudo-code:

var dict = {}; var new_item = "Bill"  If new_item not in dict: dict[new_item] = 1  else:  dict[new_item] += 1 
like image 561
user1813867 Avatar asked Sep 09 '13 02:09

user1813867


People also ask

How do you increment an object property?

To increment a value in an object, assign the value of the key to the current value + 1, e.g. obj. num = obj. num +1 || 1 . If the property exists on the object, its value gets incremented by 1 , and if it doesn't - it gets initialized to 1 .

Can you modify properties on an object?

Using the same method, an object's property can be modified by assigning a new value to an existing property. At this point, if we call the object, we will see all of our additions and modifications. Through assignment operation, we can modify the properties and methods of a JavaScript object.

How do you change the value of an object?

To change the value of an object in an array:Use the Array. map() method to iterate over the array. Check if each object is the one to be updated. Use the spread syntax to update the value of the matching object.


2 Answers

dict[key] = (dict[key] || 0) + 1; 
like image 147
snak Avatar answered Sep 30 '22 11:09

snak


@snak's way is pretty clean and the || operator makes it obvious in terms of readability, so that's good.

For completeness and trivia there's this bitwise way that's pretty slick too:

dict[key] = ~~dict[key] + 1; 

This works because ~~ will turn many non-number things into 0 after coercing to Number. I know that's not a very complete explanation, but here are the outputs you can expect for some different scenarios:

~~(null) 0 ~~(undefined) 0 ~~(7) 7 ~~({}) 0 ~~("15") 15 
like image 33
SimplGy Avatar answered Sep 30 '22 09:09

SimplGy