# Map

Use Map to run the same sequence of steps for each item in an array.

## Overview

**Type:** `map`

Map processes items one at a time. Each iteration starts with the parent context plus `item` and the zero-based `itemIndex`. Its nested steps run in order, and its outputs are not available to other iterations.

## Configuration

### Source

* **Type:** String
* **Required:** Yes, unless using the deprecated `items` template
* **Templatable:** No
* **Description:** Path to the array in context (supports dot notation for nested access)

```
users
api_response.data
batch_results.items
```

### Index by

* **Type:** String
* **Required:** No
* **Description:** Property name to use as key for results (returns object instead of array)

Use a property present on every item. Duplicate values overwrite earlier results, and missing values produce an `undefined` key.

```
id
email
userId
```

### Steps

* **Type:** Array of Objects
* **Required:** Yes
* **Description:** Workflow steps to execute for each item

Each item iteration has access to:

* `item`: The current array element
* `itemIndex`: The current iteration index (0-based)
* All original context variables

```json
[
  {
    "type": "agent",
    "output": "analysis",
    "config": {
      "provider": "openai",
      "model": "gpt-4o-mini",
      "input": "{{ item.text }}",
      "outputSchema": {
        "type": "object",
        "properties": {
          "summary": {
            "type": "string"
          }
        },
        "required": ["summary"]
      }
    }
  }
]
```

## Output

Each result is the complete context after that iteration: the parent values, `item`, `itemIndex`, and named outputs from its nested steps. Each iteration starts from the same parent context. The Map step returns different formats based on configuration:

### Array results (default)

```typescript
[
  {/* result from item 0 */},
  {/* result from item 1 */},
  {/* result from item 2 */},
];
```

### Object results (with indexBy)

```typescript
{
  "key1": { /* result for item with key1 */ },
  "key2": { /* result for item with key2 */ },
  "key3": { /* result for item with key3 */ }
}
```

### Accessing the output

```
{{ map_step[0].analysis.output }}
{{ map_step.user_123.user_details.status }}
{{ map_step | count }}
```

## Examples

These examples are steps to include in an [execution request](/docs/execute-workflows). Context blocks show the input for the preceding step; supply any other referenced values and credentials in the request's `context`.

### Simple iteration with direct source

```json
{
  "type": "map",
  "output": "enriched_users",
  "config": {
    "source": "users",
    "steps": [
      {
        "type": "request",
        "output": "user_details",
        "config": {
          "url": "https://api.example.com/users/{{ item.id }}",
          "method": "GET",
          "headers": {
            "Authorization": "Bearer {{ token }}"
          }
        }
      }
    ]
  }
}
```

**Context:**

```json
{
  "users": [
    { "id": "123", "name": "Alice" },
    { "id": "456", "name": "Bob" },
    { "id": "789", "name": "Charlie" }
  ],
  "token": "abc123"
}
```

### Nested source path

```json
{
  "type": "map",
  "output": "processed_items",
  "config": {
    "source": "api_response.data.items",
    "steps": [
      {
        "type": "agent",
        "output": "classification",
        "config": {
          "provider": "openai",
          "model": "gpt-4o-mini",
          "input": "Classify: {{ item.description }}",
          "outputSchema": {
            "type": "object",
            "properties": {
              "category": { "type": "string" }
            }
          }
        }
      }
    ]
  }
}
```

**Context:**

```json
{
  "api_response": {
    "status": "success",
    "data": {
      "items": [
        { "id": 1, "description": "Laptop computer" },
        { "id": 2, "description": "Office chair" },
        { "id": 3, "description": "Desk lamp" }
      ]
    }
  }
}
```

### Using indexBy for keyed results

```json
{
  "type": "map",
  "output": "users_by_email",
  "config": {
    "source": "users",
    "indexBy": "email",
    "steps": [
      {
        "type": "request",
        "output": "profile",
        "config": {
          "url": "https://api.example.com/profile/{{ item.id }}",
          "method": "GET"
        }
      }
    ]
  }
}
```

**Context:**

```json
{
  "users": [
    { "id": "123", "email": "alice@example.com" },
    { "id": "456", "email": "bob@example.com" }
  ]
}
```

**Output:**

```json
{
  "alice@example.com": {
    "users": [
      { "id": "123", "email": "alice@example.com" },
      { "id": "456", "email": "bob@example.com" }
    ],
    "item": { "id": "123", "email": "alice@example.com" },
    "itemIndex": 0,
    "profile": { "status": 200, "data": {}, "headers": {} }
  },
  "bob@example.com": {
    "users": [
      { "id": "123", "email": "alice@example.com" },
      { "id": "456", "email": "bob@example.com" }
    ],
    "item": { "id": "456", "email": "bob@example.com" },
    "itemIndex": 1,
    "profile": { "status": 200, "data": {}, "headers": {} }
  }
}
```

### Multi-step processing per item

```json
{
  "type": "map",
  "output": "processed_feedback",
  "config": {
    "source": "feedbacks",
    "steps": [
      {
        "type": "agent",
        "output": "sentiment",
        "config": {
          "provider": "openai",
          "model": "gpt-4o-mini",
          "input": "{{ item.text }}",
          "outputSchema": {
            "type": "object",
            "properties": {
              "sentiment": { "type": "string" },
              "score": { "type": "number" }
            }
          }
        }
      },
      {
        "type": "request",
        "output": "saved",
        "config": {
          "url": "https://api.example.com/feedback/{{ item.id }}",
          "method": "PATCH",
          "data": {
            "sentiment": "{{ sentiment.output.sentiment }}",
            "score": "{{ sentiment.output.score }}"
          }
        }
      }
    ]
  }
}
```

### Using itemIndex

```json
{
  "type": "map",
  "output": "numbered_items",
  "config": {
    "source": "items",
    "steps": [
      {
        "type": "request",
        "output": "updated",
        "config": {
          "url": "https://api.example.com/items/{{ item.id }}",
          "method": "PATCH",
          "data": {
            "position": "{{ itemIndex }}",
            "name": "{{ item.name }}"
          }
        }
      }
    ]
  }
}
```

### Batch email sending

```json
{
  "type": "map",
  "output": "emails_sent",
  "config": {
    "source": "recipients",
    "steps": [
      {
        "type": "email",
        "output": "email_result",
        "config": {
          "to": "{{ item.email }}",
          "from": "noreply@company.com",
          "fromName": "{{ company.name }}",
          "subject": "Hello {{ item.name }}!",
          "htmlPart": "<h1>Hi {{ item.name }}</h1><p>{{ item.message }}</p>",
          "textPart": "Hi {{ item.name }}\n\n{{ item.message }}"
        }
      }
    ]
  }
}
```

### Conditional processing within Map

```json
{
  "type": "map",
  "output": "notifications",
  "config": {
    "source": "orders",
    "steps": [
      {
        "type": "rule",
        "output": "notification_result",
        "config": {
          "rules": [
            {
              "conditions": [
                {
                  "source": "item.status",
                  "filter": "EQUALS",
                  "value": "shipped"
                }
              ],
              "then": [
                {
                  "type": "sms",
                  "output": "sms_sent",
                  "config": {
                    "to": "{{ item.customer.phone }}",
                    "from": "{{ company.smsNumber }}",
                    "body": "Your order #{{ item.id }} has been shipped!"
                  }
                }
              ]
            }
          ]
        }
      }
    ]
  }
}
```

### Parallel processing with Batch inside Map

```json
{
  "type": "map",
  "output": "enriched_products",
  "config": {
    "source": "products",
    "steps": [
      {
        "type": "batch",
        "output": "product_data",
        "config": {
          "steps": [
            {
              "type": "request",
              "output": "pricing",
              "config": {
                "url": "https://api.example.com/pricing/products/{{ item.sku }}",
                "method": "GET"
              }
            },
            {
              "type": "request",
              "output": "inventory",
              "config": {
                "url": "https://api.example.com/inventory/stock/{{ item.sku }}",
                "method": "GET"
              }
            },
            {
              "type": "request",
              "output": "reviews",
              "config": {
                "url": "https://api.example.com/reviews/products/{{ item.sku }}",
                "method": "GET"
              }
            }
          ],
          "mode": "all"
        }
      }
    ]
  }
}
```

## Best practices

### Performance considerations

* **Sequential execution**: Map processes items one at a time
* Batch runs an explicitly configured list of steps in parallel; it does not iterate an array automatically
* Use Batch inside Map to run independent operations in parallel within each iteration.
* Monitor execution time for large arrays
* Consider pagination for very large datasets

### Array size management

* Limit each request to an array that can finish within the endpoint's response timeout, which defaults to and is capped at 30 seconds.
* Consider breaking into smaller batches
* Use filtering before mapping when possible
* Monitor timeout settings for long-running operations

### Context access

* Access current item: `{{ item.property }}`
* Access index: `{{ itemIndex }}`
* Access original context: `{{ originalContextVar }}`
* Previous iterations don't affect subsequent ones

### indexBy usage

* Use for lookups by key
* Use unique property values. Duplicate keys overwrite earlier results.
* Returns object instead of array
* Useful for building dictionaries/maps
* Supply the property on every item; a missing property produces an `undefined` key

### Memory management

* Large arrays consume more memory
* Each iteration creates new context
* Monitor memory usage for complex steps
* Split large datasets into separate execution requests. Map does not provide a streaming result.

## Common use cases

* **Bulk data enrichment**: Enhance multiple records with external data
* **Multi-recipient notifications**: Send personalized messages to lists
* **Batch API updates**: Update multiple resources sequentially
* **Data transformation**: Convert array items to desired format
* **Sequential processing**: Process items that depend on order
* **Report generation**: Create individual reports for each entity
* **User onboarding**: Execute onboarding steps for multiple users
* **Content processing**: Analyze or classify multiple text items
* **Inventory updates**: Update stock levels for multiple products
* **Validation checks**: Validate multiple entries against rules

## Troubleshooting

### Performance issues

* Reduce number of items processed
* Optimize steps within map
* Use batch for parallelizable operations
* Consider caching repeated operations
* Monitor API rate limits

### Timeout errors

* If `options.timeout` is below 30000 milliseconds, raise it within that limit. The execute endpoint does not accept a longer response wait, and a timeout does not cancel operations already running.
* Reduce processing complexity per item
* Break into smaller batches
* Optimize external API calls

### Memory issues

* Reduce array size
* Simplify step complexity
* Process in smaller chunks
* Monitor resource usage
