Saving Array to Global

I've saved an array to a global variable using global.set
In another function, I used global.get to extract that array but only a few elements existed!
Don't know what's happening at all...

As you can see I saved it:

Then extracted it:

But instead of 16 it just returned 6 elements?

Somehow it gets affected by this node "Set Data"
image

So I changed it to:

And the global variable worked fine. Weird!
What's in the code that affected the global variable?

Probably, between set and get, msg.payload (including pfex) was modified due to code execution. I assume that if you save array variables that contain objects, that variable behaves like a pointer.

You can try the following: you convert the array variable (object) to a string, and then at get you convert it to array. Just test.

global.set('pfex', JSON.stringify(msg.payload));

then:

msg.payload = JSON.parse(global.get('pfex'));

I repeat, it's just a guess, I'm a beginner too.

In Javascript, objects are passed by reference. Arrays are just objects in JS, so the array you stored in the global context refers to the same one as the message payload.

Your "set data" function modifies that object downstream, specifically it sets msg.payload.length = 6; in line 6. That effectively truncates the array to 6 elements. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/length for reference.

Using an array object like a normal object is considered bad practice. What you should do, is creating a new object for your payload first, like msg.payload = {}, and set your properties after that.

@kuema You're absolutely correct! msg.payload.length is the culprit! Should be more careful in using this variable name next time!

You can use length nonetheless, as long as you use it on a newly created object, and not an array. Unless you explicitly want to truncate it.

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