You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js连接WebSocket服务时如何过滤指定接收方的推送通知结果

问题原因

你调用filter、find报错是因为这两个是数组方法,而你每次拿到的notification是单个独立的对象,不是数组;includes是数组或字符串方法,用在对象上自然也会报错。

实现方案

你只需要在打印前加一层字段判断即可,修改后的代码如下:

var init = function () {
  // 定义要过滤的目标接收人
  const TARGET_RECIPIENT = 'a3'
  subscription.on("data", (note) => {
    setTimeout(async () => {
      try {
        let notification = await getUpdate(note);
        // 仅to字段匹配目标值时才打印
        if (notification.to === TARGET_RECIPIENT) {
          console.log(notification)
        }
      } catch (err) {
        console.error(err);
      }
    });
  });
};

init();

如果需要把所有符合条件的通知汇总成数组存储,可以新增全局变量收集:

// 全局存储所有匹配的通知
const matchedNotifications = []
var init = function () {
  const TARGET_RECIPIENT = 'a3'
  subscription.on("data", (note) => {
    setTimeout(async () => {
      try {
        let notification = await getUpdate(note);
        if (notification.to === TARGET_RECIPIENT) {
          matchedNotifications.push(notification)
          console.log('当前匹配的通知列表:', matchedNotifications)
        }
      } catch (err) {
        console.error(err);
      }
    });
  });
};

init();

内容的提问来源于stack exchange,提问作者Jay Williams

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 23:36:03