var map = {};
map[key] = value;
How can I
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);
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;
Here you go minimize your code.
map[key] = (map[key]+1) || 1 ;
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));
}
}
Recently it could be
map[key] = (map[key] ?? 0) + 1;
Nullish coalescing operator
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..