Copying array and empty the original

Hey,
i'm new to Node-Red. I'm sorry if there is already an answer but i couldn't find any in this forum.

The function:
I want to store data in an array (Speicher1) and after a specific time, i want to copy that array (Speicher1) into another array (Speicher2) and delete/empty the original array (speicher1). Both arrays are a flow variable.

My solution:

var tempSpeicher1 = flow.get('Speicher1');

flow.set('Speicher2', tempSpeicher1);
tempSpeicher1.length= 0;
flow.set('Speicher1', tempSpeicher1);

msg.payload = 'Speicher2: ' +flow.get('Speicher2') + 'Speicher1: '+ flow.get('Speicher1');

return msg;

The problem:
After this function both of the arrays are empty.

If i delete tempSpeicher1.length = 0 it will copy the array "Speicher1" to "Speicher2".

What you are doing is setting a reference of Speicher1 to Speicher2 so when you change Speicher1 you change Speicher2.

you can get around this (depending on the contents of the array being immutable or not).

An quick (but shallow) method would be to use the spread operator like this...

var Speicher2 = [...Speicher1]; 

Thanks for your quick answer. It works for me now with this code:

var tempSpeicher1 = flow.get('Speicher1');
var tempSpeicher2 = [...tempSpeicher1];

flow.set('Speicher2', tempSpeicher2);
tempSpeicher1.length= 0;
flow.set('Speicher1', tempSpeicher1);

msg.payload = 'Speicher2: ' +flow.get('Speicher2') + 'Speicher1: '+ flow.get('Speicher1');

return msg;

Is there a way to use the spread operator directly with flow variables?

Its just JavaScript...

flow.set('Speicher2',  [...(flow.get('Speicher1') || []) ] );

the || [] part ensures it doesnt error if flow.get('Speicher1') is empty. (|| [] returns an empty array if flow.get('Speicher1') is empty/null)

Thank you.

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