Change node to set value for each object in array

I have a flow context variable that contains an array of objects. Each object has a a key/value pair with key "on" and a boolean value:

{"seg": [
        {"id": 0, "on": true},
        {"id": 1, "on": true},
        {"id": 2, "on": true}

I'm trying to use a Change node to set the "on" value to "false" for every object in the array.

Is it possible to use the Change node to update all values for "on" keys in one go? Maybe with a JSONata expression? Or will I need to create a function with a for loop to do this?

Either would work

I personally prefer JavaScript (as it is faster, more devs use JS than JSONata & so more support)

function node...

const seg = flow.get("seg");
seg.forEach(e => { e.on = false });

Thanks @Steve-Mcl

Was hoping to incorporate as one element in a longer list of changes in a single change node. Just wanting to keep things tidy. :slight_smile:

My limited JS knowledge had me hoping I could use a wildcard to change all objects simultaneously:

Failing that, I'd hoped a little JSONata expression could be used. I've found decent documentation on using JSONata as a query language, but little on using it to modify existing flow context variables.

if you can formulate the correct expression to return your data with all the on properties changed to false then re-arrange your change node to

  • SET flow.testState.seg
  • to the value J: <your expression>

Hereis an example

[{"id":"21e5e450.ab0664","type":"change","z":"c791cbc0.84f648","name":"","rules":[{"t":"set","p":"payload.seg","pt":"msg","to":"$$.payload.seg.$merge([$,{\"on\": false}])","tot":"jsonata"}],"action":"","property":"","from":"","to":"","reg":false,"x":450,"y":440,"wires":[["95b09e83.cfbe38"]]},{"id":"4dd7f307.2c34ec","type":"inject","z":"c791cbc0.84f648","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"{\"seg\": [         {\"id\": 0, \"on\": true},         {\"id\": 1, \"on\": true},         {\"id\": 2, \"on\": true}     ]}","payloadType":"json","x":200,"y":440,"wires":[["21e5e450.ab0664"]]},{"id":"95b09e83.cfbe38","type":"debug","z":"c791cbc0.84f648","name":"b","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"payload","targetType":"msg","statusVal":"","statusType":"auto","x":670,"y":340,"wires":[]}]

Thanks @E1cid

I ended up with:

$flowContext('testState') ~> | seg | { 'on': false} |

Not sure it's as elegant as your suggestion, but so far, it seems to do the trick!

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.