简体   繁体   中英

How to use associative array in JavaScript to retrieve users?

The goal is to list users in rooms, so a room can contain many users and should be easily retrieved:

ex:

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

and then

return rooms["room1"];

should return

{"username":"john","sex":"male"};
{"username":"robert","sex":"male"};

of course rooms[roomName].push(user2); is not good

Any idea on how to achieve that ?

var roomsMap = {
    room1: [],
    room2: [],
    room3: []
};

roomsMap.room1.push(user1);

or if you need the key to be dynamic:

roomsMap[roomKey].push(someUser);

EDIT:

almost good. But how to make roomsMap Dynamic as well and not be restricted to room1, room2, room3 ?

You could do it this way to dynamically add new key/array to the roomsMap .

(roomsMap[roomKey] = roomsMap[roomKey] || []).push(user1);

Complete example:

var roomsMap = {},
    user1 = {"username":"john","sex":"male"},
    roomKey = 'room1';

(roomsMap[roomKey] = roomsMap[roomKey] || []).push(user1);

console.log(roomsMap[roomKey]); //[Object { username="john", sex="male"}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM