如何在JavaScript中使用关联数组来检索用户?

时间:2013-09-13 14:54:13

标签: javascript

目标是在房间中列出用户,因此房间可以包含许多用户,并且应该可以轻松检索:

前:

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);不好

关于如何实现这一点的任何想法?

1 个答案:

答案 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"}]