That is not the ideal way to achieve what you want.
Ideally you would store the state of the item and then build a string based on the state.
e.g. you could store the sensors values an array like this...
[
{ "name": "sensor 1", "state": false },
{ "name": "sensor 2", "state": true },
{ "name": "sensor 3", "state": true },
]
or an object like this...
{
"Sensor 1": false,
"Sensor 2": true,
"Sensor 3": true
}
With an array, you could build a status string like this...
var offSensors = sensors.filter(e => e.state == false).map(e=>e.name).join(",");
//returns 'sensor 1'
var onSensors = sensors.filter(e => e.state == true).map(e=>e.name).join(",");
//returns 'sensor 2,sensor 3'
However, to update a value in the array is a bit harder (much easier with an object) so that is what i will demo...
Store sensors states in an object...
Premise...
Store a single value for each sensor named by msg.topic
in an object named sensors
in a flow context variable.
- When updating a state in flow context,
msg.topic
must hold the sensor name and msg.payload
must have the sensor value
- Demo assumes
msg.payload
will be boolean (true or false)
Example data...
{
"Sensor 1": false,
"Sensor 2": true,
"Sensor 3": true
}
//adding / updating a sensors value
var sensors = flow.get("sensors") || {}; //get the sensors state from flow context
var sensorName = msg.topic; //get sensor name from incoming msg
sensors[sensorName] = msg.payload; //store value under a key in the sensors object
flow.set("sensors", sensors); //update the flow context
getting a string of on or off sensors...
var sensors = flow.get("sensors") || {}; //get the sensors state from flow context
msg.payload = {}; //prepare the payload as an object, ready for the off and on strings
msg.payload.offSensors = Object.entries(sensors).filter(e => e[1] == false).map(e=>e[0]).join(",");
//return example 'sensor 1'
msg.payload.onSensors = Object.entries(sensors).filter(e => e[1] == true).map(e=>e[0]).join(",");
//return example 'sensor 2,sensor 3'
return msg;