首页 > 解决方案 > wss nodejs如何过滤结果?

问题描述

我正在使用 nodejs 连接到 websocket 服务器以获取更新列表。

我正在使用以下代码记录来自服务器的所有更新

var init = function () {
  subscription.on("data", (note) => {
    setTimeout(async () => {
      try {
        let notification = await getUpdate(note);
        console.log(notification)
      } catch (err) {
        console.error(err);
      }
    });
  });
};

init();

它提供了类似于下面的持续通知列表

{
  from: 'a1',
  to: 'a2',
  value: '1',
}

{
  from: 'a1',
  to: 'a3',
  value: '2',
}

{
  from: 'a2',
  to: 'a3',
  value: '3',
}

我试图过滤掉,所以只显示给指定人的通知。例如只显示到 a3 的通知。

我尝试了各种不同的方法,例如以下

        var recipient = notification.filter(function(value){ return value.to=="a3";})
        console.log(recipient);
//or
        var recipient = notification.find(o => o.to === 'a3');
        console.log(recipient);
//or
        console.log(notification.includes('a3'));

但我总是得到未定义的 var。比如notification.filter没有定义,或者notification.includes不是一个函数。

我该怎么做才能过滤掉通知?

谢谢

标签: node.jswss

解决方案


let改为使用var并确保它notification是数组,因为对象没有filterfind原型

检查这个 - > JavaScript:过滤器()对象

:)


推荐阅读