How to set a flow.context to a default value if the variable turns out to be undefined

In a function node,

how to set a flow.context to a default value, (say 0), if the variable it is expecting turns out to be undefined ?

I have this in a function node, however sometimes, the msg.payload value turns out to be undefined, (or null? I am not sure), so the function node doesn't run and gives error.

"TypeError: Cannot read properties of undefined (reading 'date')"

flow.set(["mr_1", "mr_2", "mr_3", "mr_4", "mr_5", "mr_6", "mr_7", "mr_8", "mr_9", "mr_10"],
[msg.payload[0][0].date,
 msg.payload[0][1].date,
 msg.payload[0][2].date,
 msg.payload[0][3].date,
 msg.payload[0][4].date,
 msg.payload[0][5].date,
 msg.payload[0][6].date,
 msg.payload[0][7].date,
 msg.payload[0][8].date,
 msg.payload[0][9].date]);

Your code will only ever work if the inner array objects ALL have date properties. Also, you are restricting yourself to only 10 outputs - not good if you ever need to change that.

A better approach would be something like this:

const data = Array.isArray(msg.payload) ? msg.payload[0] : []
const out = []

data.forEach( i => {
    if (i.date) out.push( i.date )
    else out.push( null )
}

flow.set( 'mr', out )

Now you only have 1 flow variable to manage and it contains the correct number of source entries.

I asked you bread , you gave me cake!!

Arrodillarse Dani Martinez GIF - Arrodillarse Dani Martinez Got Talent Espana GIFs

1 Like

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