Share This Article
Working with automation tools like n8n often involves handling lists of data – maybe it’s a batch of new leads from a form, a list of products from your e-commerce store, or results returned from an API call. This data typically arrives as an array, a collection of items. But what happens when you don’t need the entire list? Perhaps you only need the very first item, or maybe you want to filter the list to process only items that meet specific criteria. This is a fundamental task in workflow automation, and mastering it unlocks much more sophisticated and efficient processes. If you’ve ever found yourself wondering how to effectively manage these data collections in your n8n workflows, you’re in the right place. This guide will delve into the essential techniques for handling arrays, specifically focusing on **n8n: How to Get a Single Item or Filter Items from an Array**.
Why Manipulating Arrays Matters in n8n
n8n workflows are built around the concept of data flowing between nodes. Often, a node will output multiple pieces of data simultaneously, structured as an array of items. For instance, an HTTP Request node fetching data from an API might return a list of 100 user profiles, or a Read Binary File node might output multiple records from a CSV file. While processing every single item might be necessary sometimes, it’s frequently more efficient or logically correct to select or filter this data before it reaches the next step.
Consider these common scenarios:
- Processing Only New Leads: A webhook triggers your workflow whenever a form is submitted, but you only want to process leads marked with a “priority” status.
- Handling the Latest Update: An RSS feed node fetches recent blog posts, but you only need the absolute newest one to send a notification.
- Syncing Active Users: You fetch a list of all users from one application but only want to sync users whose status is “active” to another system.
- Finding a Specific Order: You retrieve multiple orders for a customer but need to isolate the one matching a specific order ID provided earlier in the workflow.
In each case, blindly passing the entire array to subsequent nodes would be inefficient, potentially causing errors or incorrect actions. Filtering or selecting specific items allows you to:
- Improve Efficiency: Reduce the number of operations performed by later nodes, saving time and resources.
- Ensure Accuracy: Process only the relevant data, preventing mistakes or unwanted side effects.
- Simplify Logic: Make downstream nodes easier to configure by providing them with precisely the data they expect.
- Control Flow: Route different types of items down different paths in your workflow based on criteria.
Understanding how to manipulate these arrays is therefore not just a “nice-to-have” but a core skill for building robust and effective n8n automations.
Understanding n8n Data Structure: Items and JSON
Before diving into the methods, it’s crucial to grasp how n8n represents data flowing between nodes. When a node outputs multiple results, it typically does so as an array of objects. In n8n terminology, each object in this array is referred to as an “item”.
Each item usually contains two main properties:
json
: This holds the primary data payload for the item, typically structured as a JSON object (key-value pairs). This is where you’ll find the actual information you want to work with (e.g., username, email, status, order ID).binary
: This property exists if the item contains binary data, like a file.
For most data manipulation tasks involving filtering or selection based on content, you’ll be working almost exclusively with the json
property.
Imagine a node outputs two items representing user profiles. The data structure might look something like this conceptually:
[ // Item 1 { "json": { "userId": 101, "name": "Alice", "status": "active", "email": "alice@example.com" }, "binary": {} // Usually empty if no file data }, // Item 2 { "json": { "userId": 102, "name": "Bob", "status": "inactive", "email": "bob@example.com" }, "binary": {} }]
When you configure nodes like the IF node or write code in the Function node, you need to tell n8n how to access the specific piece of data within an item’s json
property. For example, to check the status of an item, you’d typically refer to {{ $json.status }}
in expression editors (like in the IF node) or item.json.status
in the Function node (where `item` represents the current item being processed).
Forgetting the .json
part is a very common source of errors, especially when starting with the Function node. Always remember that the data you usually care about resides *inside* the json
object of the item.
Method 1: Filtering Items with the IF Node (No-Code)
The simplest and most common way to filter items based on specific conditions without writing any code is by using the IF Node. This node acts like a conditional gatekeeper: it examines each incoming item against rules you define and routes the item based on whether it meets those conditions.
Think of it as a bouncer at a club checking IDs. If an item meets the entry criteria (the condition is true), it gets sent through one door (the “true” output). If it doesn’t, it gets sent through another door (the “false” output) or simply turned away (if the false output isn’t connected).
How to Use the IF Node for Filtering
- Add the IF Node: Place an IF Node in your workflow immediately after the node that outputs the array you want to filter.
- Configure Conditions:
- Click on the IF Node to open its parameters.
- Under “Conditions”, click “Add Condition”.
- You’ll define a rule here. This typically involves comparing a value from the incoming item’s data to a specific value or another data point.
- Value 1: This is where you specify the data field you want to check within the incoming item. Use n8n’s expression editor. Remember the data structure! You’ll likely need to reference the `json` property. For example, to check the `status` field, you would enter:
{{ $json.status }}
. The expression editor helps you find available fields. - Operation: Choose the comparison operator (e.g., “Equals”, “Not Equals”, “Contains”, “Greater Than”, “Is Empty”).
- Value 2: Enter the value you want to compare against (e.g., “active”, “completed”, 100). This can be a fixed value or another expression.
- You can add multiple conditions using “AND” or “OR” logic if needed.
- Connect Outputs: The IF Node has two outputs:
- True Output (Top): Items that satisfy ALL the conditions you set will exit through this output. Connect this to the next node that should process the *filtered* items.
- False Output (Bottom): Items that *do not* satisfy the conditions will exit here. You can connect this to another part of your workflow (e.g., to handle rejected items) or leave it unconnected if you simply want to discard the items that don’t match.
Use Case Example: Filtering Active Users
Imagine a “Get Users” node fetches a list of users, each with a `status` field (either “active” or “inactive”). You only want to send a welcome email to active users.
- Node “Get Users” outputs an array of user items.
- Connect “Get Users” to an IF Node.
- In the IF Node:
- Condition -> Value 1:
{{ $json.status }}
- Condition -> Operation: “Equals”
- Condition -> Value 2:
active
- Condition -> Value 1:
- Connect the True Output of the IF Node to your “Send Email” node.
- Leave the False Output unconnected (or connect it to an archive step if needed).
Now, only items where the `status` is exactly “active” will pass through to the “Send Email” node.
Pros and Cons of the IF Node
Pros:
- No-Code: Easy to use for non-programmers.
- Visual: Clearly shows the filtering logic in the workflow diagram.
- Standard: The intended way to handle basic conditional routing in n8n.
Cons:
- Less Flexible: Can become cumbersome for very complex filtering logic involving many conditions or intricate checks.
- Limited Transformations: Primarily for routing; doesn’t easily allow modifying the data within the item during filtering.
For straightforward, condition-based filtering (e.g., status equals X, value is greater than Y), the IF Node is almost always the best and easiest choice.
n8n Best Practice
Method 2: Getting the First (or N) Item(s) with the Item Lists Node (No-Code)
What if your goal isn’t to filter based on content, but simply to select items based on their position in the array? The most common requirement here is getting only the first item. For this, n8n provides another convenient no-code solution: the Item Lists Node.
The Item Lists node is designed for various operations on entire lists (arrays) of items, such as summing values across items, merging items, splitting items, and crucially for our purpose, limiting the number of items passed through.
How to Use the Item Lists Node to Get the First Item
- Add the Item Lists Node: Place this node after the node outputting the array you want to trim.
- Select Operation: Open the Item Lists Node parameters. In the “Operation” dropdown, select “Limit”.
- Set the Limit: A “Limit” field will appear. Enter the maximum number of items you want to pass through.
- To get only the first item, set Limit to
1
. - To get the first 5 items, set Limit to
5
.
- To get only the first item, set Limit to
- Connect Output: The Item Lists node (in Limit mode) has a single output. Connect this to the next node in your workflow. Only the specified number of items (starting from the first one) will be passed on.
Use Case Example: Processing the Most Recent Entry
Suppose an “HTTP Request” node fetches the latest 10 comments from an API, ordered from newest to oldest. You only want to process the single most recent comment (which is the first item in the array).
- Node “Get Comments” outputs an array of 10 comment items.
- Connect “Get Comments” to an Item Lists Node.
- In the Item Lists Node:
- Operation: Limit
- Limit:
1
- Connect the output of the Item Lists Node to the next step (e.g., “Format Notification”).
Only the very first item (the newest comment) from the original array will proceed.
Pros and Cons of the Item Lists Node (Limit Operation)
Pros:
- Extremely Simple: Very easy and quick for getting the first item(s).
- No-Code: No programming required.
- Clear Intent: The node’s purpose (limiting items) is obvious in the workflow.
Cons:
- Position-Based Only: Can only select items based on their order in the array, not their content.
- Limited Scope: Only useful for “take the first N” scenarios. Cannot select items from the middle or end easily, nor filter based on data values.
If your requirement is purely “I need only the first item” or “I need the first X items”, the Item Lists node with the Limit operation is the perfect tool.
n8n Tip
Method 3: Advanced Control with the Function Node (Code)
While the IF and Item Lists nodes cover many common scenarios, sometimes you need more power and flexibility. You might need to implement complex filtering logic, select items based on intricate calculations, or even modify items *while* filtering them. This is where the Function Node comes into play.
The Function Node allows you to write custom JavaScript code to process incoming items. It offers unparalleled control but requires a basic understanding of JavaScript and n8n’s data structures.
Accessing Data in the Function Node
Inside the Function Node’s code editor, the entire array of items arriving from the previous node is available via a variable named items
. This is a standard JavaScript array.
Each element within the `items` array is an n8n item object. As discussed earlier, the actual data payload is typically within the .json
property of each item.
- To access the first item object:
items[0]
- To access the JSON data of the first item:
items[0].json
- To access a specific property (e.g., “uuid”) of the first item’s JSON data:
items[0].json.uuid
- When iterating (e.g., using `map` or `filter`), you’ll often use a variable like `item` to represent the current item being processed. In that context, you’d access its data via
item.json.propertyName
.
Crucially: The Function Node expects you to return an array of items as its output. Even if you are only outputting a single item, it must be wrapped in an array.
Sub-section: Getting the First Item with Code
While the Item Lists node is easier for this, you can also select the first item using the Function Node. This might be useful if you need to perform other complex actions simultaneously.
JavaScript Code:
// Access the incoming items array// (provided automatically by n8n as 'items')// Check if there are any items to prevent errorsif (items.length > 0) { // Get the first item object const firstItem = items[0]; // IMPORTANT: Return the item wrapped in an array // as n8n expects an array of items as output. return [firstItem];} else { // If no items came in, return an empty array // to avoid errors downstream. return [];}// Use code with caution.
Explanation:
items.length > 0
: This check prevents errors if the previous node happened to output an empty array.const firstItem = items[0];
: Accesses the first element (the first item object) from the `items` array.return [firstItem];
: Returns the selected item, but enclosed in square brackets `[]` to make it an array containing just that one item, fulfilling n8n’s requirement.return [];
: Ensures that if the input was empty, the output is also a valid (empty) array.
Note: While functional, this is overkill if *only* getting the first item is needed – use the Item Lists node for that.
Sub-section: Filtering Items with Code
The Function Node truly shines when you need more sophisticated filtering than the IF node allows. You can leverage standard JavaScript array methods like .filter()
.
JavaScript Code Example (Filter for ‘completed’ status):
// Access the incoming items array ('items')// Use the JavaScript array filter methodconst filteredItems = items.filter(item => { // Access the 'status' property within the json data of the current item // Return true if the item should be kept, false otherwise return item.json.status === 'completed';});// Return the new array containing only the filtered itemsreturn filteredItems;// Use code with caution.
Explanation:
items.filter(item => { ... })
: This standard JavaScript function iterates over each `item` in the `items` array.item.json.status === 'completed'
: Inside the filter function, this condition checks if the `status` property within the `json` object of the current `item` is equal to “completed”.- The `filter` method automatically builds a new array (`filteredItems`) containing only those items for which the condition returned `true`.
return filteredItems;
: The Function Node outputs this newly created, filtered array.
You can implement much more complex logic within the filter condition, check multiple fields, perform calculations, or even call external libraries if needed (though that’s more advanced).
Sub-section: Accessing Data from Other (Not Directly Connected) Nodes
Sometimes, your filtering logic in a Function Node might depend on data produced by a node earlier in the workflow, not just the immediately preceding one. n8n provides special variables for this:
$node["Node Name"].data
: This accesses the output data of the first item from the node named “Node Name”. Use the actual name of the node as displayed in your workflow editor. Be cautious, as this only gives you the data from the *first* item outputted by that node.$item(index).$node["Node Name"].data
: This is more advanced and useful when nodes are running in parallel for each item (e.g., after a Split in Batches node). It attempts to access the data from “Node Name” that corresponds to the item at the same `index` as the current item being processed by the Function node. The `index` variable is often available within loops or methods like `.map()`.
Important Consideration: The Function node itself only accepts one direct input connection. If you need to combine data from multiple branches or use data from several preceding nodes reliably *before* your Function node logic, you should first use a Merge Node to bring those data streams together into a single input array for the Function node.
Pros and Cons of the Function Node
Pros:
- Maximum Flexibility: Implement any filtering or selection logic possible with JavaScript.
- Data Transformation: Can modify item data during the filtering/selection process.
- Powerful: Handles complex conditions, calculations, and interactions with data from other nodes.
Cons:
- Requires Code: Need basic JavaScript knowledge.
- Less Visual: The logic is hidden within the code editor, not immediately visible on the workflow canvas.
- Error Prone: Syntax errors or logical mistakes in the code can break the workflow. Requires careful testing.
- Steeper Learning Curve: Understanding `items`, `item.json`, and the expected return format takes practice.
Use the Function Node when no-code options (IF, Item Lists) are insufficient for your complex filtering, selection, or data transformation needs. Remember the golden rule: access data via
item.json.propertyName
and always return an array of items.Function Node Guideline
Choosing the Right Method: A Quick Guide
With three distinct methods available, how do you decide which one to use for your specific task? Here’s a simple decision guide:
- Do you need to filter items based on the value of their data (e.g., status = “active”, amount > 100)?
- YES: Use the IF Node. It’s the standard, no-code way for conditional routing. Only consider the Function Node if the logic is exceptionally complex.
- Do you need to select only the first item (or the first few items) based purely on their position in the array?
- YES: Use the Item Lists Node with the “Limit” operation. It’s the simplest and most direct way.
- Do you need to:
- Implement very complex filtering logic involving multiple checks, calculations, or custom functions?
- Select items based on criteria not easily handled by the IF node?
- Modify the data within items *while* filtering or selecting them?
- Access data from non-adjacent previous nodes within the logic?
- YES (to any of the above): Use the Function Node. It provides the necessary power and flexibility, but be prepared to write JavaScript.
In summary:
- Simple conditions? IF Node.
- First item(s) by position? Item Lists Node (Limit).
- Complex logic, custom selection, or data transformation? Function Node.
Troubleshooting Common Issues
When working with array filtering and selection, you might encounter a few common pitfalls:
- IF Node Not Filtering Correctly:
- Double-check your expressions in Value 1. Did you remember
$json.
before the property name (e.g.,{{ $json.status }}
not{{ status }}
)? - Verify the data type comparison. Are you comparing a number to a string? Use type conversions in expressions if necessary (e.g.,
{{ parseInt($json.amount) }}
). - Check the exact value in Value 2. Is it case-sensitive? Are there leading/trailing spaces?
- Double-check your expressions in Value 1. Did you remember
- Item Lists Node Not Outputting Anything:
- Ensure the previous node actually outputted items. Check its output data.
- Verify the “Limit” value is greater than 0.
- Function Node Errors:
- “Cannot read properties of undefined (reading ‘propertyName’)”: This often means you tried to access `item.json.propertyName` but `item.json` didn’t exist or the property itself was missing. Add checks (e.g., `if (item.json && item.json.status)`). Most commonly, it means you forgot `.json` and tried `item.propertyName`.
- Syntax Errors: Carefully check your JavaScript for typos, missing brackets `{}`, parentheses `()`, or semicolons `;`.
- Incorrect Output Format: Remember to always `return` an array of items, even if it’s just one item `[item]` or an empty array `[]`. Returning a single object directly will cause errors.
- Errors Handling Empty Input: Add checks like `if (items.length > 0)` before trying to access `items[0]` or filtering an empty array.
- Accessing Data from Other Nodes (`$node`) Fails:
- Make sure the “Node Name” used in `$node[“Node Name”]` exactly matches the node’s name in the editor (case-sensitive).
- Remember `$node[“…”]` usually only gets the *first* item’s data from that node. If you need data corresponding to the current item, investigate using `$item(index).$node[…]` or merge data first.
Testing your workflow with sample data and examining the input/output of each node is crucial for debugging these kinds of issues.
Related Reading
Conclusion: Mastering Array Manipulation in n8n
Effectively handling arrays – specifically knowing **n8n: How to Get a Single Item or Filter Items from an Array** – is a cornerstone of building powerful and efficient automations. Whether you need the simplicity of the no-code IF Node for conditional filtering, the directness of the Item Lists Node for selecting the first item(s), or the ultimate flexibility of the Function Node for complex logic, n8n provides the tools you need.
By understanding the structure of n8n items (especially the crucial .json
property) and choosing the appropriate node for your task, you can precisely control the flow of data, process only what’s necessary, and build more robust, reliable workflows. Don’t be afraid to experiment with each method; start with the no-code options for simpler tasks and gradually explore the Function node as your requirements become more complex. Mastering these techniques will significantly elevate your n8n automation skills.