3

I'm trying to add a key to an object if it doesn't exist, or increase its count if it's already present. The following code correctly adds the new key if it doesn't exist, but doesn't increase its count if it already does. Instead it returns {UniqueResult1:NaN, UniqueResult2:NaN}.

let detectionHash = {};
    function onDetected(result) {
        detectionHash[result.code]++;
        if(detectionHash[result.code] >= 5) {
          //here's where I want to be
        }
    }

How can I increase the count of the key if it already exists?

1
  • 1
    complete code and how are you are using it to get the unexpected behaviour Commented Aug 11, 2018 at 19:36

2 Answers 2

11

You could take the value or the default value of zero and add one.

A not existing property returns an undefined, which is falsy. The following logical OR || checks this value and take the next value of zero for incrementing.

detectionHash[result.code] = (detectionHash[result.code] || 0) + 1;
Sign up to request clarification or add additional context in comments.

2 Comments

Would this not replace the object keys? What I'm really looking for is to store the count of each unique key. The second part (unique key) I figured out, just not the first part.
No, that would only change the value for that specific key.
0

If you ask for a key that doesn't exists, it will be of "undefined" type:

var abc=[];
abc[5] = 'hi';
console.log(typeof abc[3]); //it will be "undefined", as a string (in quotes)

So:

let detectionHash = {};
    function onDetected(result) {
        //does the key exists?
        if (typeof detectionHash[result.code] !== "undefined") 
            detectionHash[result.code]++; //exist. increment
        else
            detectionHash[result.code]=0; //doesn't exist. create
        if(detectionHash[result.code] >= 5) {
          //here's where I want to be
        }
    }

1 Comment

0 or 1. You don't say what value you want in your new key

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.