Sorry for another noob question but I'm missing the typical OR function to test mulitple values in a function node. I was trying to avoid having to have lots of extra change nodes.
I want to test payload and change as required so "1",1,True,"ON" are changed to "ON" and "0",0,"false","OFF" are changed to "OFF"
I have done a lot of searching and it seemed that the switch command may fit the bill but it doesn't seem to work for me.
Is there a neat wat to do this in a function node please ?
There are various ways. I don't think the switch node will help much unless you want to learn JSONata which can be made to do this.
However, in a function, you either use a long-winded if
statement or a more readable switch
statement.
const x = msg.payload
if ( x === "1" || x === 1 || x.toLowerCase() === 'on' .... ) { .... }
switch (x) {
case '1':
case 1:
case 'ON':
....
// do something
break
default:
// do something different
}
Personally, I try to make sure that I rationalise all of my inputs before processing them so that I don't have to worry about this when dealing with actual logic.
There is a 3rd method (which would also be best in JSONata probably) which is to use an array and a filter function. More complex but the nice thing is that it never gets more complex no matter how many choices you end up with. I use that when processing the list of possible libraries available to uibuilder. The list comes from a file and could be of any arbitrary length.
If you want to do it with a standard node you can use the Change node for this sort of thing
1 Like
Thanks I was nearly there ... but tried to use switch (msg.payload) directly.
Just to say that Simon's reply is what I was referring to when saying that I try to rationalise input data early. It makes any further processing SOOO much easier.
Thanks to both of you for the very quick replies, I did already have a change node like that, but wanted one catch all function node.
The issue is that with a number of different devices requiring different outputs I have to send the correct payloads to and from switch nodes to correctly operate and display current status on dashboard. This function IS a way to rationalise things by adding this to the switch outputs I can now store the logical state ON or OFF in one global object with Device and State.
Thanks again much appreciated.