How to check if an Reference in msg.payload exists?

Sometimes i get following reference in msg.payload and sometimes not.

msg.payload.Test

How can i check in a function if the reference 'Test' in payload exists or not?

payload always exists but sometimes with 'Test' and sometimes without.

If not exists i get following Error.
ReferenceError: references is not defined

I tried:
"if (msg.payload.hasOwnProperty("Test")){do something}"

But i don't know if i used it correctly or it is the right commando.

Anybody an idea?
Thanks in advise.
UweG

There are a few ways to do it, and the one you've identified, the hasOwnProperty function, is certainly a way to be sure it exists.

if (msg.payload.hasOwnProperty("Test")){
  // do something
}

One thing to be careful of is this check only tests if there is a property called Test. The value of the property could still be null or otherwise blank. So depending on your scenario, you may want to also check the value of Test before using it.

1 Like

Thank's for your quick help.
It works fine for me.
Greetings
UweG

I have this:

var obj = msg.payload[0];
var regen2;
if (msg.payload.hasOwnProperty("rs_neerslag")) {
    regen2 = obj["rs_neerslag"];
}
else{
    // not found...
    regen2 = 0;
}

and this is what comes into the function node (from mysql):

SELECT rs_neerslag FROM regensensor WHERE rs_ts >= "2022-12-01:00:00:00" AND rs_ts <= "2022-12-01:23:59:59" ORDER BY rs_ts ASC LIMIT 1; : msg.payload : array[1]
array[1]
0: object
rs_neerslag: "3521.7"

and the result is that regen2 = 0....
I believe it used to work. Has it someting to do with the new version? (I recently upgraded to 3.0.2)

Your result is in element 0 of the array in payload. So that's where you need to test...

if (msg.payload[0].hasOwnProperty("rs_neerslag")) {

Or

if (obj.hasOwnProperty("rs_neerslag")) {

However you should probably check the payload is actually an array AND that it's length is >= 1 before you try to access payload[0]