Function with multiple outputs

Hi,
I use often function with multiple outputs;
If I need to send payload = "ON" (only one value) I write this function ....

var msg1 = {payload:"ON", topic:"light"}

but when I need to send payload = {"state":"ON"}

how I can write the msg1 ?

var msg1 = { ??? , topic:"light"}
1 Like

Maybe like this?

var msg1 = {payload: msg.payload.state, topic:"light"}

var msg1 = { payload: {state:“ON“} , topic:"light"};

1 Like

If you need to return a message like that, payload should be an object and not a string or a number.

You can either declare a variable and define it as an object, then assign payload that variable (option 1), or just type it in the payload (option 2).

Option 1 (using a temporary variable, then assigning it to msg.payload):

var output = {};

// some code here?

output.state = "ON";

// some more code here?

msg.topic = "light";
msg.payload = output;
return msg;

Option 2 (working directly on the msg):

// some code first?

msg = { topic: "light", payload: {state: "ON"}};
return msg;

If you want to use the payload directly, you can also do it like this, note that I clear the msg payload first to make sure there are no variables other than the one you need:

// some code first?

msg.topic = "light";
msg.payload = {}; // this will clean the existing payload
msg.payload.state = "ON"; // adds the property and assigns it the value

return msg;

Using either option is a matter of personal preference. I tend to work on temporary variables, do all the operations there, and assign it to msg in the end.
It wouldn't be the first time I unadvertently modify or overwrite the payload, clearing the previous value, then try to read another value contained in it and does not work, or I get a wrong value. Working as in option 1 prevents that. But if the function is simple enough, where you only have to read a handful of values, it shouldn't be a problem.

Hope this helps.

1 Like
msg = { topic: "light", payload: {state: "ON"}};

Ok, this works for me.

Thank you very much for help :+1:

Thank you for explanation ....

You're welcome :slight_smile:

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