1

I am trying to remove a piece of a data from a JSON array. For example, I have this array;

var users = [];
io.on('connection',function(socket){
   socket.on('nickname', function(nick){
      socket.nick = nick;
       users.push({
         user:socket.nick,
         userid:socket.id,
         socket:socket
       });
    });

I am trying to delete in users this way;

socket.on('disconnect', function(){
    delete users[{
        user,
        userid,
        socket
    }];
   });
 });

How can I do that?

3
  • are you trying to delete a specific user, or the whole array? Commented Jul 25, 2017 at 18:41
  • Do you want to delete the whole users array or only a specific object in it? Commented Jul 25, 2017 at 18:42
  • Each connected user has its own nickname and id on that page.Disconnected user will be deleted in users array. Commented Jul 25, 2017 at 18:46

2 Answers 2

3

You may try using lodash methods to achieve what you are trying to: -

var _ = require('lodash');
socket.on('disconnect', function(){
        _.pullAllWith(users, [{
             user:socket.nick,
             userid:socket.id,
             socket:socket
             }], _.isEqual)
       });
     });

see if this works..

Sign up to request clarification or add additional context in comments.

Comments

0

If you know the values of each of the properties of each user object, you could pass the values into a function and loop through the the users array to find a matching object and then splice it from the array (updated answer to pass in object to function):

var users = [];
for (var i = 1; i < 10; i++) {
  users.push({
    user: i,
    userId: i,
    socket: i
  });
}

/**
 * Loop through the users array to find matching 
 * object to remove
 **/
var deleteUser = function(userToDelete) {
  for (var userObj in users) {
    var userObject = users[userObj];
    if (typeof userObject === "object" &&
      userObject.user === userToDelete.user &&
      userObject.userId === userToDelete.userId &&
      userObject.socket === userToDelete.socket) {
      users.splice(userObj, 1);
      break;
    }
  }
  console.log(users);
};

deleteUser({
  user: 2,
  userId: 2,
  socket: 2
});

2 Comments

Each connected user has its own nickname and id on that page.Disconnected user will be deleted in users array.İts not a static like 1 or 2 .
No, I know it's not a static. I just did the "i" count to have an example users array for you to see.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.