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.
>Solution :
Create the key and property if it doesn’t exist, if it already exists increase its value by 1.
let numusers = {},
inroom = "room1",
addRoom = numusers[inroom] === undefined ? numusers[inroom] = 1 : numusers[inroom] = numusers[inroom]+1;
console.log(numusers);