Function block: Create loops for/each

Hi,
Apparently I can’t code a for or each loop in the function block.
Could you confirm that this feature is not available?
Thanks!

Hello,

You have any “loop” mechanic you might want. In our docs for the function node we outline:

Only base JavaScript functionality is available for the execution of this code - no external libraries or modules are available for use.

This just means that modules from npm aren’t available to you, but you can do most anything else you would expect in/with JavaScript. It’s worth mentioning that we also have a loop node, which may be all you need.

Below are some examples showing just some of the ways you can loop over data. They might help you explore your particular situation. If you are still stuck, provide some specifics and I’d be happy to help out.

Rob


Given a payload:

{
  "data": {
    "bar": [1, 2, 3, 4, 5]
  }
}

And a function node with the following:

const double = x => x * 2;

// `for` loop example
payload.data.forLoop = [];
for (let i = 0; i < payload.data.bar.length; i++) {
  payload.data.forLoop[i] = double(payload.data.bar[i]);
}

// `for/of` loop example
payload.data.forOfLoop = [];
for (let val of payload.data.bar) {
  payload.data.forOfLoop.push(double(val));
}

// `forEach` example
payload.data.forEachLoop = [];
payload.data.bar.forEach((val, i) => {
  payload.data.forEachLoop[i] = double(val);
});

// `map` example
payload.data.mapLoop = payload.data.bar.map(double);

return payload;

The output is:

{
  "data": {
    "bar": [
      1,
      2,
      3,
      4,
      5
    ],
    "forLoop": [
      2,
      4,
      6,
      8,
      10
    ],
    "forOfLoop": [
      2,
      4,
      6,
      8,
      10
    ],
    "forEachLoop": [
      2,
      4,
      6,
      8,
      10
    ],
    "mapLoop": [
      2,
      4,
      6,
      8,
      10
    ]
  }
}