Saving array to flow variable

Hi,

I am having an issue to saving an array to a flow variable:

var l = flow.get("l") || []
l.push(msg.payload)
flow.set("l", l)
return l;

From my understanding of the documentation and the forum. this should get the array from the flow and then append the array, however, it always warps each object in additional array. As seen here:

Screenshot 2023-11-15 173944

I want this as ['value', 'value']

What am I doing wrong?

[{"id":"ac8ddef2a4f9cad8","type":"inject","z":"a8c551010c2bc0bc","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"value","payloadType":"str","x":210,"y":660,"wires":[["156ea39e637c0279"]]},{"id":"156ea39e637c0279","type":"function","z":"a8c551010c2bc0bc","name":"function 2","func":"var l = flow.get(\"l\") || []\nl.push(msg.payload)\nflow.set(\"l\", l)\nreturn l;","outputs":1,"timeout":0,"noerr":0,"initialize":"","finalize":"","libs":[],"x":440,"y":660,"wires":[["03ed314908d9848a"]]},{"id":"03ed314908d9848a","type":"debug","z":"a8c551010c2bc0bc","name":"debug 11","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":600,"y":660,"wires":[]}]

You must always return a message object from a function node. Also nowadays you should be using let or const rather than var, thought that is not an issue here. Try this

let l = flow.get("l") || []
l.push(msg.payload)
flow.set("l", l)
msg.payload = l
return msg

As you are returning l which would produce
"Function tried to send a message of type string"

Try return {payload: l};

Return l is causing a object referencing issue and creating the 1 element arrays in you context var.

Thanks @Colin and @E1cid for pointing out that I need to return a message object. That was a head scratcher, maybe the error message here should be a bit more forthcoming... I really strugle to understand why returning l changes it but fixed is fixed for now :slight_smile:

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