Constructing Multiple Outputs

I’m new here, so please excuse any inexact terminology.

Input to a node with 3 outputs consists of an array: [34, 35, 36]

matchVar = 35

Function iterates over the array. Where a match is found, the corresponding msg.payload is set to {"On": true}. Where it does not match msg.payload becomes {"On": false}

I've got this far, but I am not constructing the output correctly:

var matchVar = 35; //test value
var outmsg = {};
var inputArray = msg.payload; // [34, 35, 36]
var outputArray = [];
var i;
for (i = 0; i < inputArray.length; i++) {
    if (inputArray[i] == switchedOn) {
        outmsg.payload={"On": "true"};
    }else{
        outmsg.payload={"On": "false"};
    }
    outputArray.push(outmsg.payload);
}
return outputArray;

I (think I) know that the output should look like: [ msg1, msg2, msg3] where msg1.payload is {"On": "true"}, msg2.payload is {"On": "false"} and msg3.payload is {"On": "true"}, but I am getting tangled up.

Not bad for a newbie.

So what you need to do is build an output array too.

So you have the three checks.

I am not a programmer. But from your code:

for (i = 0; i < inputArray.length; i++) {
    if (inputArray[i] == switchedOn) {
        outmsg.payload={"On": "true"};
    }else{
        outmsg.payload={"On": "false"};
    }
    outputArray.push(outmsg.payload);
}

Make it something like:

for (i = 0; i < inputArray.length; i++) {
    if (inputArray[i] == switchedOn) {
        outmsg[i].payload={"On": "true"};    //  look at what I did here.
    }else{
        outmsg[i].payload={"On": "false"};   //  and here.
    }
    outputArray.push(outmsg.payload);
}

That way you have an outmsg[i] array.

Then at the end you do:

return [outmsg[0].payload,outmsg[1].payload, outmsg[2].payload]

Basically it is:
return [payload1, payload2, payload3]

And you have to set the node to have 3 outputs.

Again, I shall stress: I do not know how to write code.
But that is basically how you would do it.

Others could possibly reply and correct my mistake.

Good luck and enjoy Node-Red.

There are two common mistakes.

  1. You are using the same message and thus overwriting the previous payload.
  2. to feed multiple outputs, a complete message (including payload) is required, you just push the payload

So something like this should work (not tested):

for (i = 0; i < inputArray.length; i++) {
    let outmsg = {}; // create new message object for each output
    if (inputArray[i] == switchedOn) {
        outmsg.payload={"On": "true"};
    }else{
        outmsg.payload={"On": "false"};
    }
    outputArray.push(outmsg); // output the complete message object
}

Alternatively, you could reuse the input message and clone it with RED.util.cloneMessage(msg) each time. That way you can preserve existing properties.

Aha!

Thank you. I'd been really tangled-up with this, but I get it now.

1 Like

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