Function node to keep same topic

hi so i want to do something relly basic change a string message that comes from mqtt from 0 to 1 and from 1 to 0 i tried to do it with a change node but i put both options inside but it only does one and not both


so itried the funktion node and it works perfectly but i lose the topic which is really important ,ho do i keep the same topic?

if (msg.payload === "1") {
   msg = { payload:"0" };
} else {
   msg = { payload:"1" };
}
return msg;

In your code you are creating a whole new message and returning it.

It's a better habit to reuse the msg object you've been given - as that then preserves the other properties:

if (msg.payload === "1") {
   msg.payload = "0";
} else {
   msg.payload = "1";
}
return msg;

hi thanks for your fast response cause i am new with java script and learning now can show me what you mean ?
thanks
chris

Hi @Giaitzoglou

I provided exactly the code you could use in my reply.

Where you were doing:

msg = { payload:"0" };

I changed it to:

msg.payload = "0";

In your code, you were assigning msg to a new object - so it lost all of the other properties on the message.
In my code, we keep the existing msg object and just update its payload.

ohhh sorry i unsderstand now can i ask you why it didnt work in the change node ?

The Change node applies each rule you set in the order you list them.

This means:

  • if payload is 1, the first rule does nothing, the second rule changes it to a 0. That is good.
  • if payload is 0, the first rule will change it to a 1. The second rule then finds that 1 and changes it back to a 0. That is bad.

thanks a lot for your help

Try using a intermediary value in the change node;

change

example

[{"id":"3c3eae5.ea3d352","type":"change","z":"c53060.842a0fa","name":"","rules":[{"t":"change","p":"payload","pt":"msg","from":"0","fromt":"str","to":"3","tot":"str"},{"t":"change","p":"payload","pt":"msg","from":"1","fromt":"str","to":"0","tot":"str"},{"t":"change","p":"payload","pt":"msg","from":"3","fromt":"str","to":"1","tot":"str"}],"action":"","property":"","from":"","to":"","reg":false,"x":430,"y":1120,"wires":[["f6be0d0a.725f2"]]},{"id":"9fd5b2ee.1fa62","type":"inject","z":"c53060.842a0fa","name":"","topic":"","payload":"0","payloadType":"str","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":190,"y":1090,"wires":[["3c3eae5.ea3d352"]]},{"id":"f6be0d0a.725f2","type":"debug","z":"c53060.842a0fa","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":650,"y":1120,"wires":[]},{"id":"977b5120.e3654","type":"inject","z":"c53060.842a0fa","name":"","topic":"","payload":"1","payloadType":"str","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":190,"y":1140,"wires":[["3c3eae5.ea3d352"]]}]
1 Like

This is one of the few cases where I would use JSONata

image

3 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.