36
var map = {};
map[key] = value;

How can I

  • assign value 1 if key does not yet exist in the object
  • increment the value by 1 if it exists

Could I do better than:

if (map[key] == null) map[key] = 0;
map[key] = map[key]++;
3
  • 2
    Try if (typeof map [key] === "undefined") to check for inexistence. Normally something that doesnt exist in your map will be undefined. Not null. Commented Sep 20, 2016 at 9:52
  • Can't you just use hasOwnProperty to check for the existence of the prop you are looking for ? Commented Sep 20, 2016 at 10:10
  • 6
    Possible duplicate of Javascript Object increment item if not exist Commented Apr 13, 2019 at 16:52

9 Answers 9

57

Here you go minimize your code.

map[key] = (map[key]+1) || 1 ;
Sign up to request clarification or add additional context in comments.

13 Comments

By "flag hoisting" you mean "short-circuit evaluation". This doesn't have anything to do with hoisting, although "flag hoisting" is an amusing conflation.
without having flag hoisting property in JavaScript. You can not use so called "short-circuit evaluation". Ultimately, Its utilizing the same concept.
There is no kind of hoisting involved in your code at all.
You're misreading that question. var a = a || 1; would involve hoisting because of the var keyword (the local variable is hoisted). Here you're manipulating a property of an existing object, therefore there's nothing that would get hoisted anywhere.
@ricky: nope. Getting a value by non-existing key returns undefined (without any invisible assignment). undefined + 1 gives NaN, which is a falsey value, so the control goes to || 1 part. I assure you nothing is being hoisted here. Go read up on the term.
|
18

Recently it could be

map[key] = (map[key] ?? 0) + 1;

Nullish coalescing operator

Comments

6

You can check if the object doesn't have the specific key and set it or increase existing key value by one:

function assignKey(obj, key) {
  typeof obj[key] === 'undefined' ? obj[key] = 1 : obj[key]++;
}

var map = {};

assignKey(map, 2);
assignKey(map, 2);
assignKey(map, 4);
assignKey(map, 1);
assignKey(map, 2);
assignKey(map, 5);
assignKey(map, 1);
console.log(map);

Comments

5

ES6 provides a dedicated class for maps, Map. You can easily extend it to construct a "map with a default value":

class DefaultMap extends Map {

    constructor(defVal, iterable=[]) {
        super(iterable);
        this.defVal = defVal;
    }

    get(key) {
        if(!this.has(key))
            this.set(key, this.defVal);
        return super.get(key);
    }
}

m = new DefaultMap(9);
console.log(m.get('foo'));
m.set('foo', m.get('foo') + 1);
console.log(m.get('foo'))

(Ab)using Objects as Maps had several disadvantages and requires some caution.

1 Comment

The code snippet has an error; Uncaught SecurityError. I'm not sure if this is a problem with the code itself or with some StackOverflow issue. Just thought I'd point it out.
3

you can use ternory operator like this

 map[key] ? map[key]++ : map[key] = 1;

Comments

1

It would be better if you convert array's value into integer and increment it. It will be robust code. By default array's value is string. so in case you do not convert it to integer then it might not work cross browser.

if (map[key] == null) map[key] = 0;
map[key] = parseInt(map[key])+1;

3 Comments

parseInt(undefined) is NaN.
have you also declared value of key ?
Also, "by default array's value is string" is just rubbish, and there are no arrays in the question.
0
function addToMap(map, key, value) {
    if (map.has(key)) {       
        map.set(key, parseInt(map.get(key), 10) + parseInt(value, 10));
    } else {
        map.set(key, parseInt(value, 10));
    }       
}

Comments

0

Creating an object:

    tagObject = {};
    tagObject['contentID'] = [];  // adding an entry to the above tagObject
    tagObject['contentTypes'] = []; // same explanation as above
    tagObject['html'] = [];

Now below is the occurrences entry which I am addding to the above tag Object..

ES 2015 standards: function () {} is same as () => {}

          let found = Object.keys(tagObject).find(
                (element) => {
                    return element === matchWithYourValueHere;
                });

          tagObject['occurrences'] = found ? tagObject['occurrences'] + 1 : 1;

this will increase the count of a particular object key..

Comments

0

The shortest code would be:

map[key] = ++map[key] || 1

Comments

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.