There are two fields value I want to wright to a DB - "rxRate" and "txRate".
Now some times the server responds with these fields missing or undefined, how can I handle this? If it is missing or undefinde I want to make the field = 0.
let rxRate = msg.payload.rxRate;
let txRate = msg.payload.txRate;
if(rxRate == undefined){
let rxRate = 0
}
if(txRate == undefined){
let txRate = 0
}
msg.payload = {
eui: msg.payload.eui,
online: msg.payload.online,
rxRate: msg.payload.rxRate,
txRate: msg.payload.txRate
}
'''
PS - I know my function is not close on correct.
And the same for the other variable. by using let again inside the if block you were defining a new variable of the same name, that was only valid inside the block. Comparing directly with undefined will generally work but is generally considered bad practice as undefined is effectively a global variable that can be overwritten.
In fact since you are setting the variables to 0 you can do if (!rxRate) rxRate = 0
since an undefined variable is considered false. You could not use that technique if you were setting it to a non-zero value as if rxRate were already 0 then it would set rxRate to that non-zero value.
Error: A 400 Bad Request error occurred: {"error":"unable to parse 'ttnGateway eui=\"7076FF0056070218\",online=true,rxRate=undefined,txRate=undefined': invalid boolean"}
Now in this instance the two fields are not in the json, how do I handle that?
If msg.payload.rxRate does not exist then it will be undefined, so the answer is yes.
Rather than delete all the properties you don't want (assuming you really do need to delete them, it is very rare to have to delete properties) then it would be better as
Yes, however, strictly speaking msg is an object and it's properties are objects/strings/numbers etc. JSON is just a string format. So msg = {} actually means set msg to a new empty object. (sorry, not meaning to be pedantic)
For Colin's example to work, you'd have to store the properties msg.payload.eui and msg.payload.online in temporary variables before setting msg to a new empty object.