简体   繁体   中英

How do I find an object by object inside a javascript array

I'm storing websocket connections inside an array. These are objects. And I'd like to remove a connection from the array when the connection is closed.

Is there any way I can find which connection object matches the closing connection and unset it?

I don't think indexOf works, right? Because the value is an object...

.........................................

here's some code

var connections = [];

websocketServer.on('request', function(request) {
  var connection = request.accept(null, request.origin);

  connection.on('message', function(message){
    if(message.type !== 'utf8')
      return;

    var msg = JSON.parse(message.utf8Data);

    if(msg.txt == 'something'){
      connections.push(connection);
    }

  });

  connection.on('close', function(connection) {
    // here remove connection object from connections array

  });
});

You can do indexOf then splice

var index = connections.indexOf(connection);
if(~index) connections.splice(index,1);

Use underscore.js and call _.isEqual(object, other);

Underscore is a utility-belt library for JavaScript that provides a lot of the functional programming support that you would expect in Prototype.js (or Ruby), but without extending any of the built-in JavaScript objects. It's the tie to go along with jQuery's tux, and Backbone.js's suspenders.

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