Appending a key value pair to a javascript object

2019-09-07 01:34发布

问题:

This question already has an answer here:

  • Dynamically access object property using variable 12 answers

This is similar to this question. However, I want to add a property to an object but I don't know the name of that property. The scenario is that I have some users connecting to a namespace in my socket.io app, when a user connects a random socket.id is generated to be able to differentiate that user from the rest of the users, when the user connects they also send their gender to the server (via socket.emit), now I want to create an object that keeps track of the users' socket ids and genders.

var users = {};               // create empty object 
var specialID = socket.id;    // get user's socketid
var gender;                   // suppose gender contains their gender (male or female)

now I tried

users.specialID = gender;

but that changes the specialID property of the users object every single time a user connects. It doesn't add a new property/value pair (who's property is the specialID (socket.id) and who's value is the gender of the user). It sounds kind of stupid but I don't know how to do it.

回答1:

Try this:

users['your key'] = gender;