This drives me nuts. Must be a simple error somewhere...
my function want to retrieve the length of 2 global arrays:
var se = global.get("sensors");
var sn = se.length;
var li = global.get("lights");
var ln = li.length;
var m = { payload: { "# lights": ln, "# sensors": sn }};
return (m)
However the returned values in the NR debugger are:
{object
# lights: undefined
# sensors: undefined
}
i used the length function in other nodes, the global arrays are defined. Whats missing here?
Are you sure?
Update your function to this:
const se = global.get("sensors")
const sn = se ? se.length : 0
const li = global.get("lights")
const ln = li ? li.length : 0
node.warn({
se,
seType: typeof se,
seIsArray: Array.isArray(se)
li,
liType: typeof li,
liIsArray: Array.isArray(li)
})
msg.payload = { "# lights": ln, "# sensors": sn }}
return msg
and show us what you see.
Good idea!
The global variables are array of objects....
So length should return a result???
Never used the the node.warn function
Look closer at your screenshot.
its NOT an array - its a JS object.
e.g.
const anArray = [{}, {}, {}]
const anObject = { "prop": "value" }
If you want the number of props (keys) in the object, then use Object.keys(se || {}).length
2 Likes
ah yes! a classical pitfall! thanks a lot, also for the hint with the node.warn function which seems to be perfect for debugging.
Cherio!
system
Closed
2 September 2023 16:12
8
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.