Array as Input
Some workflows need to perform the same operation on every item in an array. This example demonstrates how to use .foreach()
to iterate over a list of strings and apply the same step to each one, producing a transformed array as the output.
Repeating with .foreach()
In this example, the workflow uses .foreach()
to apply the mapStep
step to each string in the input array. For each item, it appends the text " mapStep"
to the original value. After all items are processed, step2
runs to pass the updated array to the output.
src/mastra/workflows/example-looping-foreach.ts
import { createWorkflow, createStep } from "@mastra/core/workflows";
import { z } from "zod";
const mapStep = createStep({
id: "map-step",
description: "adds mapStep suffix to input value",
inputSchema: z.string(),
outputSchema: z.object({
value: z.string()
}),
execute: async ({ inputData }) => {
return {
value: `${inputData} mapStep`
};
}
});
const step2 = createStep({
id: "step-2",
description: "passes value from input to output",
inputSchema: z.array(
z.object({
value: z.string()
})
),
outputSchema: z.array(
z.object({
value: z.string()
})
),
execute: async ({ inputData }) => {
return inputData.map(({ value }) => ({
value: value
}));
}
});
export const loopingForeach = createWorkflow({
id: "foreach-workflow",
inputSchema: z.array(z.string()),
outputSchema: z.array(
z.object({
value: z.string()
})
)
})
.foreach(mapStep)
.then(step2)
.commit();
Run this example with multiple string inputs.
Workflows (Legacy)
The following links provide example documentation for legacy workflows: