I document here a piece of flow I have used recently.
The desired format was a msg object with this structure:
{"sensor1" : 8}
The value should be random and the sensor name should be fixed but configurable.
This is how the flow looks like:
Each inject node will generate a random integer number from 1 to 9. The upper limit can be changed by adjusting the content of msg.payload in the configuration dialog box of the node. Note that the name of the sensor is configured as the topic of the message as it will be used in the following node.
The function node will generate the random values and will format the msg.payload to the desired format.
Here is the code inside the function node:
let value = Math.floor(Math.random() * msg.payload + 1)
msg.payload = {[ msg.topic ] : value};
return msg;
Note here the use of the destructuring pattern with computed values. In this case, the computed value is whatever is the value in msg.topic.
Here is an output from the debug node after randomly pressing different node buttons:
Flow:
[{"id":"c22aa68d.3dd668","type":"inject","z":"1f275547.b32ebb","name":"","topic":"sensor1","payload":"9","payloadType":"num","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":124.10000610351562,"y":67.00000476837158,"wires":[["726a491e.723d58"]]},{"id":"726a491e.723d58","type":"function","z":"1f275547.b32ebb","name":"Format sensor output","func":"let value = Math.floor(Math.random() * msg.payload + 1)\nmsg.payload = {[msg.topic] : value};\ndelete msg.topic;\nreturn msg;","outputs":1,"noerr":0,"x":354.1000747680664,"y":146.00000381469727,"wires":[["706fefa4.1fe6a"]]},{"id":"991eae59.37e98","type":"inject","z":"1f275547.b32ebb","name":"","topic":"sensor2","payload":"9","payloadType":"num","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":122.00000381469727,"y":121,"wires":[["726a491e.723d58"]]},{"id":"91074579.4b1d58","type":"inject","z":"1f275547.b32ebb","name":"","topic":"sensor3","payload":"9","payloadType":"num","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":122.00000381469727,"y":173,"wires":[["726a491e.723d58"]]},{"id":"f4a4b20b.45016","type":"inject","z":"1f275547.b32ebb","name":"","topic":"sensor4","payload":"9","payloadType":"num","repeat":"","crontab":"","once":false,"onceDelay":0.1,"x":118.00000381469727,"y":224,"wires":[["726a491e.723d58"]]},{"id":"706fefa4.1fe6a","type":"debug","z":"1f275547.b32ebb","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":559.1000366210938,"y":145,"wires":[]}]