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]++;
var map = {};
map[key] = value;
How can I
Could I do better than:
if (map[key] == null) map[key] = 0;
map[key] = map[key]++;
Here you go minimize your code.
map[key] = (map[key]+1) || 1 ;
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);
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.
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;
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));
}
}
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..