Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

220
Views
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:

    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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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")

about 4 years ago · Juan Pablo Isaza Report

0

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>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!