目标是在房间中列出用户,因此房间可以包含许多用户,并且应该可以轻松检索:
前:
user1 = {"username":"john","sex":"male"};
user2 = {"username":"robert","sex":"male"};
user3 = {"username":"isac","sex":"male"};
rooms["room1"].push(user1);
rooms["room1"].push(user2);
rooms["room2"].push(user3);
然后
return rooms["room1"];
应该返回
{"username":"john","sex":"male"};
{"username":"robert","sex":"male"};
当然rooms[roomName].push(user2);
不好
关于如何实现这一点的任何想法?
答案 0 :(得分:3)
var roomsMap = {
room1: [],
room2: [],
room3: []
};
roomsMap.room1.push(user1);
或者如果您需要密钥是动态的:
roomsMap[roomKey].push(someUser);
编辑:
差不多好。但如何使房间地图动态,而不是 仅限于room1,room2,room3?
您可以通过这种方式动态添加新密钥/数组到roomsMap
。
(roomsMap[roomKey] = roomsMap[roomKey] || []).push(user1);
完整示例:
var roomsMap = {},
user1 = {"username":"john","sex":"male"},
roomKey = 'room1';
(roomsMap[roomKey] = roomsMap[roomKey] || []).push(user1);
console.log(roomsMap[roomKey]); //[Object { username="john", sex="male"}]