简体   繁体   English

如何在JavaScript数组中按对象查找对象

[英]How do I find an object by object inside a javascript array

I'm storing websocket connections inside an array. 我将websocket连接存储在数组中。 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? 我认为indexOf无效,对吗? 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 你可以先做indexOf然后splice

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

Use underscore.js and call _.isEqual(object, other); 使用underscore.js并调用_.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. Underscore是JavaScript的实用程序带库,它提供了Prototype.js(或Ruby)中期望的许多功能编程支持,但没有扩展任何内置的JavaScript对象。 It's the tie to go along with jQuery's tux, and Backbone.js's suspenders. 这是与jQuery的晚礼服和Backbone.js的吊带一起使用的纽带。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在对象数组 Javascript 中过滤数组 object? - How do I filter an array object inside of a array of objects Javascript? 如何在 JavaScript 中的另一个对象中找到具有属性的对象 - How do I find objects with a property inside another object in JavaScript 如何在 javascript 数组中找到对象值? - how do I find an object value in a javascript array? 如何查找对象是否包含JavaScript中的数组? - How do i find if an object contains an array in javascript? jQuery-如何在对象内的数组内查找特定的JavaScript对象? - jQuery - how to find a specific JavaScript object inside an array within an object? 如何在javascript中的另一个对象数组中找到数组的长度 - How to find length of an array inside another array of object in javascript Javascript 如果 object 在数组中,我如何调用 object 的元素? - Javascript how can I call an element of an object if the object is inside an array? 如何动态地在JavaScript中的数组上的对象内部创建对象 - How can I dynammicaly create an object inside a object, on a array in JavaScript JavaScript:如何访问另一个对象内部的对象原型? - JavaScript: How do I access the prototype of an object inside another object? 如何在javascript中访问对象内部的对象 - How do I access an object inside of an object in javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM