Appending a key value pair to a javascript object

2019-09-07 01:53发布

This question already has an answer here:

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条回答
老娘就宠你
2楼-- · 2019-09-07 02:19

Try this:

users['your key'] = gender;
查看更多
登录 后发表回答