Appending a key value pair to a javascript object [duplicate]

人走茶凉 提交于 2019-12-12 05:48:51

问题


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;


来源:https://stackoverflow.com/questions/31912657/appending-a-key-value-pair-to-a-javascript-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!