The code below is used to construct an object array:
var users = {};
var user = {};
user[socket.id] = data.username;
if(users[data.roomname]){
// Room already exists - check if user already exists
// if data.username does not exist in users then:
users[data.roomname].push(user);
}
else{
// New room
users[data.roomname] = [user];
}
After a few iterations, the array looks like this:
console.log ( 'Users: ', users );
users { RoomABC:
[ { YidwzgUHPHEGkQIPAAAD: 'Mr Chipps' },
{ 'JG-gtBMyPm0C1Hi1AAAF': 'Mr T' },
{ '2JFGMEdPbgjTgLGVAAAH': 'Mr Chipps' }, ] }
The main issue is ensuring that each username is unique, so Mr Chipps
should not be added again if that name already exists.
Most solutions assume the keys are known. I have attempted several methods including some
, indexOf
but have not been successful in simply checking if UserX already exists.
The following block of code is my latest attempt to only add the user if it is not already present in the object array. While it works, it seems rather cumbersome with nested loops and counters:
if(users[data.roomname]){
// Room already exists - check if user already exists
let found = 0;
// Nested loop - although functional, it feels inelegant
Object.keys(users[data.roomname]).forEach(key => {
Object.keys(users[data.roomname][key]).forEach(key2 => {
if ( users[data.roomname][key][key2] === data.username ) {
found++;
}
});
});
if ( found == 0 ) {
users[data.roomname].push(user);
}
}
I am still searching for a cleaner one-liner solution for this existence check, but haven't found one yet.