user1813867
user1813867

Reputation: 1055

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

Upvotes: 51

Views: 31020

Answers (7)

nurmdrafi
nurmdrafi

Reputation: 529

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);

Upvotes: 0

Macro
Macro

Reputation: 1

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");
}

Upvotes: 0

RobG
RobG

Reputation: 147453

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];

Upvotes: 1

snak
snak

Reputation: 6703

dict[key] = (dict[key] || 0) + 1;

Upvotes: 148

SimplGy
SimplGy

Reputation: 20437

@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

Upvotes: 25

James LeClair
James LeClair

Reputation: 1294

You can use the ternary operator (?:) like this:

dictionary[key] ? 
    dictionary[key].value += 1 : 
    dictionary[key] = {value: 1};

Upvotes: 3

Blender
Blender

Reputation: 298364

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]++;

Upvotes: 4

Related Questions