Function returns a string instead of an array

Hi there,
i m a newbee and try to execute a function code in node red.
my function is supposed to return me an array but instead i got the message error "Function tried to send a message of type string"

Here is my code

var out = ;

for (var i = 0; i < msg.payload.length; i++) {
if (msg.payload[i].col2 !==null)
{

  if (msg.payload[i].col2=="x" )
   {
     var tmp= msg.payload[i].col1;
     out.push(tmp);
   }
}

}
return [out];

so the goal is to go through an csv sheet which has 2 column, the first one containing a list of attribute and the second one containing cross. i want to extract only the column 1 attribute where the corresponding column 2 has a cross

here is a template of my csv sheet
image

Function must return an object. So easiest is just to replace the payload of the existing msg.
So
return { payload: out }:

Hi,
thanks for your answer.
but is an array not an object?
i tried this "return { payload:out };" but it is not returning anything. I guess it is because my current message does not have a payload value?

Sorry I need a coffee...
Should have been

msg.payload = out;
return msg;

Strictly speaking yes an array is an object, but we mean/need a generic one with properties that can be added and extended.

Understood thanks.
but still returning nothing :frowning:
i don t know if i miss something else...

var out = ;

for (var i = 0; i < msg.payload.length; i++) {
if (msg.payload[i].col2 !==null)
{
if (msg.payload[i].col2=="x" )
{
var tmp= msg.payload[i].col1;
out.push(tmp);

   }
}

}

msg.payload = out;
return msg;

I don't see any way that can return nothing. What do you see if you feed it into a debug node ? Also what do you see in a debug node showing the input to the function?
If you actually mean that the message payload sent is an empty array then probably there are no records that pass the tests.
You can debug your function using node.warn(), for example, at the beginning you could put

node.warn(`Length is ${msg.payload.length}`)

and it will show the length in the debug pane.

i m sorry,
i think , i also need a coffee...
i forgot to connect my debug node.
now it is working thanks!

You can tidy your function up a bit as follows if you like

var out = [];

for (var i = 0; i < msg.payload.length; i++) {
if (msg.payload[i].col2 !==null  &&  msg.payload[i].col2=="x" )
{
  out.push( msg.payload[i].col1);
}
msg.payload = out;
return msg;

In fact you don't even need the null test as msg.payload[i].col2 will evaluate to undefined if it does not exist so it will fail the test even if it is null. You would need it in some languages but not javascript.

2 Likes