How to increment a value in a JavaScript object?

前端 未结 7 1012
时光说笑
时光说笑 2021-02-12 13:50
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
相关标签:
7条回答
  • 2021-02-12 13:55

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

    0 讨论(0)
  • 2021-02-12 13:58

    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;
    
    0 讨论(0)
  • 2021-02-12 13:59

    Here you go minimize your code.

    map[key] = (map[key]+1) || 1 ;
    
    0 讨论(0)
  • 2021-02-12 14:03
    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));
        }       
    }
    
    0 讨论(0)
  • 2021-02-12 14:07

    Recently it could be

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

    Nullish coalescing operator

    0 讨论(0)
  • 2021-02-12 14:07

    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 affffding 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..

    0 讨论(0)
提交回复
热议问题