I have an object that is initially empty but it will eventually look like this:
numusers = { room1 : 1, room2 : 5, room3 : 2};
this will always be different according to the circumstances. If some user enters room1 then room1 should be created at that very moment and value will be 1, if other user enters room2 likewise but if another user enters room1 then the value will have to increase to 2 and so on.
I tried this:
numusers = { room1 : 1, room2 : 5, room3 : 2};
let initnum = 0; //the initial value each room will have
var inroom = "room1"; //this is the room this user entered
numusers.push({ inroom : ++initnum });
it didnt work and I cant figure out a different approach. What should I do here?
Thank you.
numusers is an object, not an array.
If you want to set the value of a property, you can use bracket notation:
let initnum = 0;
var inroom = "room1";
numusers = {};
numusers[inroom] = initnum
console.log(numusers)
To increment when duplicate keys are entered, you can first check whether the property exists:
newusers = {}
function process(room){
newusers[room] = newusers[room] ? newusers[room]+1 : 1;
console.log(newusers)
}
process("room1")
process("room1")
process("room2")
Create the key and property if it doesn't exist, if it already exists increase its value by 1.
It is definitely cleaner the way @Spectric wrote it:
numusers[inroom] = numusers[inroom] ? numusers[inroom]+1 : 1;
Which means the same as I suggest, setting directly the key of the room to the value it requires, either plus 1 if it exists or create if it doesn't.
Below I included an example with a select option.
const numusers = {};
const roomSelect = document.querySelector('#rooms');
roomSelect.addEventListener('change', function() {
let inroom = this.value;
numusers[inroom] = numusers[inroom] ? numusers[inroom]+1 : 1;
console.log(numusers);
});
<select name="room" id="rooms">
<option value="room1">Room 1</option>
<option value="room2">Room 2</option>
<option value="room3">Room 3</option>
</select>