How to increment a value in a JavaScript object?

前端 未结 7 1032
时光说笑
时光说笑 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 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..

提交回复
热议问题