'How to increment an object property value if it exists, else set the initial value?
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
Solution 1:[1]
dict[key] = (dict[key] || 0) + 1;
Solution 2:[2]
@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
Solution 3:[3]
Your pseudo-code is almost identical to the actual code:
if (key in object) {
object[key]++;
} else {
object[key] = 1;
}
Although I usually write:
if (!(key in object)) {
object[key] = 0;
}
object[key]++;
Solution 4:[4]
You can use the ternary operator (?:) like this:
dictionary[key] ?
dictionary[key].value += 1 :
dictionary[key] = {value: 1};
Solution 5:[5]
You should check if the object has an own property with the new_item name first. If it doesn't, add it and set the value to 1. Otherwise, increment the value:
var dict = {};
var new_item = "Bill"
dict[new_item] = dict.hasOwnProperty(new_item)? ++dict[new_item] : 1;
The above is a bit wasteful as if the property exists, it increments it, then assigns the new value to itself. A longer but possibly more efficient alternative is if the property doesn't exist, add it with a value of zero, then increment it:
if (!dict.hasOwnProperty(new_item)) {
dict[new_item] = 0;
}
++dict[new_item];
Solution 6:[6]
You can do this in a lot of ways. In general if you want to know if an Object has a key you use the in modifier with the key name. This looks like:
var key = "key name";
var dict = {};
var hasKey = (key in dict);
Though you can check if a value is set by simply testing if it is undefined. This being that in JavaScript if you don't have a value initialized and send it through an if statement it will act as a false. Which looks like:
var dict = {};
if(dict[key]) {
print("key: " + dict[key]);
} else {
print("Missing key");
}
Solution 7:[7]
If value exist then (prev value + 1) OR set initial value 1.
const obj = {};
addToObj = key =>{
// Using ternary operator
obj[key] = obj[key] ? (obj[key] + 1) : 1;
}
addToObj('alex');
addToObj('adam');
addToObj('maria');
addToObj('maria');
addToObj('alex');
addToObj('john');
addToObj('jack');
addToObj('rock');
console.log(obj);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Rob Bednark |
| Solution 2 | SimplGy |
| Solution 3 | Blender |
| Solution 4 | Ernest Friedman-Hill |
| Solution 5 | Rob Bednark |
| Solution 6 | BenMorel |
| Solution 7 | nurmdrafi |
