[Solved] Mutate Current Item in Loop Node

It would be helpful to be able to directly mutate the current item in the Loop node and have those changes be persisted back to the loop source.

I’m trying to create an endpoint that returns an array of devices, and also includes the status state for each device in the response.

The use case is to loop over an array of device objects, retrieve state for each device within the loop, and add that state to the current device object for the loop. If I use the Gauge Query node and set the payload path to loopCurrentItem.value.status, this mutation seems to get lost on the next iteration. (Seems like the loopCurrentItem is just over-written on each iteration.) The documentation makes it sound like if you include a Next node in the loop, it will retain modifications to the payload, but that doesn’t seem to happen for the current loop item.

As a work-around I’m using a Function node within the Loop to place the status state back on the corresponding device object in the array:

const status = payload.loopCurrentItemStatus; // The result of the Gauge Query for the device's status
const index = payload.loopCurrentItem.index;
payload.devices[index].status = status;

I imagine that mutating the current item within a loop will be a common scenario. It would be great if the Loop node allowed for direct manipulation of the current item.

I haven’t seen your workflow so I don’t know what you’ve tried so far, but import the attached workflow for an example of how to accomplish this without a function node.

mutate-loop-example-develop.flow.zip (1.4 KB)

The gist is we’re mutating currentItem.value however we please, and then we’re using an Array Node to replace the original array’s value at our current index (available at currentItem.index) with the value of currentItem.value.

Make sure you have a Return Node at the end of the run to save your changes into the next iteration, or else any mutations you make within the loop will be lost.

Great, thanks for the example. That makes sense, I’ll use the Array node’s Replace At operation instead of a Function.

So just to clarify, if a Return node is not used within the Loop, after the iterations are complete then the entire payload is reset to before the Loop started?

That’s correct. A Return Node or a Break Node is required within your loop if you want your payload changes to carry over to the next iteration and to any nodes running after the loop.

1 Like