1

I am using nodejs to connect to a websocket server to pull a list of updates.

I am using the following code which logs all updates from ther server

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

init();

which provides an ongoing list of notifications similar to below

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

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

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

I am trying to filter out so only notifications which are to a specified person are shown. For example only show notifications which are to a3.

I have tried various different methods such as the following

        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'));

but I always get var not defined. Such as notification.filter is not defined, or notification.includes is not a function.

What can I do to filter out the notifications?

Thanks

  • It's not clear where you're trying to do this filtering. If it's an array the code shown filters it just fine. Are you sure you're not trying to filter it before the data has completed arriving? – Dave Newton Sep 16 '21 at 16:02

1 Answers1

0

Use let instead var and make you sure that notification is array, couse Object doesn't have filter and find prototype

check this -> JavaScript: filter() for Objects

:)

Cube
  • 1