Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create an object with variables as keys?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading