I am using a pretty simple function node to, based on a zone change, output a message to send to my Sonos using the tts-ultimate node. I am not proficient at JS. This is how I’m doing it, but maybe it’d be better to set up some kind of array? If so, how would that look?
if (msg.payload === "home") {
msg.payload = "Tammy has arrived home";
} else {
msg.payload = "Tammy has arrived at work";
}
return msg;
I do not think that can be done much better with that notation type.
There might be another notation type with : ? and other characters that are shorter in characters, but not more efficient in the execution and that one can be a bit more tricky to read for others.
Thanks for the replies. Actually wrote a method to handle it easier. Just need to keep adding to the array.
let tamZone=[
["salon","Tammy has arrived at Evelia's Salon"],
["home","Tammy has arrived home"],
["swpg","Tammy has arrived at work"]
]
let zlen = tamZone.length;
for (let i = 0; i < zlen; i++) {
node.warn(tamZone[i][1]);
node.warn(msg.payload);
if (tamZone[i][0] == msg.payload) {
msg.payload = tamZone[i][1];
}
}
return msg;
let tamZone={
salon: "Tammy has arrived at Evelia's Salon",
home: "Tammy has arrived home",
swpg: "Tammy has arrived at work"
}
mag.payload = tamZone[msg.payload];
return msg
Many programming languages support arrays with named indexes.
Arrays with named indexes are called associative arrays (or hashes).
JavaScript does not support arrays with named indexes.
In JavaScript, arrays always use numbered indexes.
I haven’t been able to try it since I have been on vacation but it should work.
Here is about associative arrays (objects is probably the correct name) in JavaScript.