I'm asking here because if I don't ask, I won't get an answer.
Yes, I can test it myself but going on past history for me I still need to ask.
(Otherwise I would do just that and it will fail so I have to ask all the same.)
Code:
const channels = flow.get("channels");
let x = channels[msg.payload].number;
//msg.payload = x.number;
msg.payload = x;
return msg;
This is an exert from the flow"chanels":
(ok, from the function node that sets it.)
"bold": { "number": 166 },
"peach": { "number": 167 },
"foxone+2": { "number": 201 },
"abcHD": { "number": 202 },
This is because I HAD the last one named as abd-HD rather than abcHD.
The - sign somehow confused the lookup.
So my question stands will the + will do the same?
UPDATE:
Ok, I stuffed up.
So now the problem is:
How can I catch the error if the channel name is not found?
In that function node.
Hi @Trying_to_learn
You can apply Optional Chaining to stop an exception.
let x = channels[msg.payload]?.number; /* x will be undefined, if the key is not found */
if(x !== undefined){
// do something with x
}
I have used !== undefined as 0 can be falsey, so if you happen to have a number of 0, it will evaluate to false, so instead ACTUALLY check if the type is undefined
Thanks.
But that doesn't address the problem if I send it a channel name that isn't in the list.
I have (been digging) and this seems to work.
const channels = flow.get("channels");
const check = channels[msg.payload];
if (check == undefined) throw("Channel not found");
let x = channels[msg.payload].number;
//msg.payload = x.number;
msg.payload = x;
return msg;
You only just beat me to the reply.
Yup, what I put is basically the same thing, just slightly shorter,
let x = channels[msg.payload]?.number; /* x will be undefined, if the key is not found */
if(x !== undefined){
// do something with x
}
else{
throw("Channel not found");
}
Oh, sorry...
What you said there MAY work for what I want.
I am still not understanding all the short hand writing of ?. and what you did.
I'll look into that structure and see if I can remember that for next time.
I'll slightly re-do it so the fail is the first part.
I'll put it in the code so I see it and it may prompt me to use it next time.
Again Thanks.
No worries
? in this context, will check if there is a value to continue with, if there is not, return undefined
channels["Non-existing-key"].number // exception
channels["Non-existing-key"]?.number // undefined
I have that site book marked - in the bigger picture.
Now I have the fun job of learning all those tricks.
