Check if key exists in an array and replace its value

Viewed 9103

CLIENT CODE

I am sending an id of a client from the client side using

var socket = io.connect('http://localhost:8080?token='+userID);

and getting it on the server in my io.on('connection') function using

SERVER CODE

let token = socket.handshake.query.token;

so now I have the userID stored in the variable token.

Also I am getting the connected socket id and storing it like

var id = socket.id;

Then I am storing the userID and the socketID in an array as key value pair.

var item = {};
item[token] = id;

This is an array I am pushing it into(the array is declared outside the on connection function)

keyPairArray.push(item);

So I am getting an array like this when two people are connected.

[ { '10': 'HvlunYNFCcF5vK0-AAAA' },
  { '1456': '17XF7mbh4vYr2WUSAAAB' } ]

But when any user reloads the page the array gets like

[ { '10': 'HvlunYNFCcF5vK0-AAAA' },
  { '1456': '17XF7mbh4vYr2WUSAAAB' },
  { '1456': 'tIhvkxFbSSAQEckWAAAC' } ]

Same user Id but different socket id's.

The socket id changes every time the user reloads the page or opens the page in another tab and the same UserID is appended into the array with a different socket id.

I don't want to insert the same user again. If the user reloads the page, I want it to check the userId which is the key in the array and replace the old socket id with the newly generated one.

This is the code that I tried with no luck

var checkKeyPair = keyPairArray.some(function(item){
    return item[token] === id;
});

if(checkKeyPair){
    console.log("Hello");
}else{
    keyPairArray.push(item);
    console.log(keyPairArray);
}
3 Answers

Try this (if ES6 is not a problem):

let token = socket.handshake.query.token;
var id = socket.id;
var item = { [token]: id };
var index = keyPairArray.findIndex(it => Object.keys(it)[0] === token);
if (index === -1) {
    keyPairArray.push(item);
} else {
    keyPairArray[index] = item;
}

You can combine Array#some with Object.keys to check if there is an user with given userId, something like that:

const users = [{
    '10': 'HvlunYNFCcF5vK0-AAAA'
  },
  {
    '1456': '17XF7mbh4vYr2WUSAAAB'
  }
];

function checkIfUserExists(userId) {
  return users.some((user) => Object.keys(user).indexOf(userId) > -1)
}

console.log(checkIfUserExists('10'));
console.log(checkIfUserExists('11'));

var users = [{
    '10': 'HvlunYNFCcF5vK0-AAAA'
  },
  {
    '1456': '17XF7mbh4vYr2WUSAAAB'
  }
];



function saveUser(newUserId) {


  users.forEach(function(key) {

    if (Object.keys(key)[0] == newUserId)
      console.log('user exists');
    else {
      var item = {};
      item[newUserId] = 'fsdfsdgdfsgdfhgf55665hftgh56';
      users.push(item);
    }
  });
}

saveUser('1456');

Related