Home > Blockchain >  How to create an object with variables as keys?
How to create an object with variables as keys?

Time:11-15

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 }); 
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

it didnt work and I cant figure out a different approach. What should I do here?

Thank you.

CodePudding user response:

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)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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")
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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);
<iframe name="sif4" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related