n8n循环处理完全指南

一、使用Split In Batches节点实现可视化循环

适用场景:批量处理大量数据(如100条新闻分10批处理)

  1. 添加Split In Batches节点

  2. 配置节点参数:
  • 批量大小(Batch Size):10
  • 输入数据:{{ $json.items }}
  1. 在循环体中处理单条数据

  2. 使用"循环完成"连接后续节点

示例配置

// 输入数据表达式

{{ $node["RSS获取"].json["items"] }}

// 循环体内访问当前项

{{ $json.title }}

{{ $json.summary }}

二、在Code节点中使用JavaScript循环

1. forEach循环处理关键词数组

// ... existing code ...

// 处理关键词并添加分类标签

let categorizedKeywords = [];

$json.keywords.forEach(keyword => {

  // 定义关键词分类映射

  const categories = {

    "技术趋势": ["GPT-4", "大模型", "生成式AI"],

    "核心技术": ["深度学习", "神经网络", "自然语言处理"],

    "头部企业": ["OpenAI", "谷歌", "百度", "微软"]

  };

  

  // 查找关键词所属分类

  let category = "其他";

  for(const [cat, keywords] of Object.entries(categories)) 

  {

    if(keywords.includes(keyword)) {

      category = cat;

      break;

    }

  }

  

  categorizedKeywords.push({

    name: keyword,

    category: category

  });

});

return {

  title: $json.title,

  pubDate: $json.pubDate,

  summary: $json.summary,

  keywords: categorizedKeywords,

  rating: $json.rating,

  link: $json.link

};

// ... existing code ...

2. map方法处理数组生成HTML列表

// 将新闻列表转换为HTML列表

{{ $json.items.map(item => `

  <div class="news-item">

    <h3>${item.title}</h3>

    <p>${item.summary.substring(0, 100)}...</p>

    <div class="meta">${item.pubDate}</div>

  </div>

`).join('') }}

如果是多条输入一起处理的模式,请使用下面代码:

{{ $input.all().map(item => `
<h1>${item.json.output.title}</h1>
        <div class="news-item">
            <h3 class="title">${item.json.output.title}</h3>
            <div >
                ${item.json.output.pubDate}
                <span class="rating">${item.json.output.rating}</span>
            </div>
            <p class="summary">${item.json.output.summary}</p>
            <p><span class="keywords">关键词:</span> ${item.json.output.keywords.join(', ')}</p>
            <p><a href="${item.json.output.link}" class="link" target="_blank">请阅读原文</a></p>
        </div>
`)}}

3. for循环实现嵌套数据处理

// 处理包含嵌套结构的新闻数据

let result = [];

for(let i = 0; i < $json.news.length; i++) {

  const news = $json.news[i];

  

  // 处理嵌套的相关文章

  let relatedArticles = [];

  if(news.related && news.related.length > 0) {

    for(let j = 0; j < news.related.length; j++) {

      relatedArticles.push({

        id: news.related[j].id,

        title: news.related[j].title,

        // 只保留必要字段

      });

    }

  }

  

  result.push({

    title: news.title,

    pubDate: news.pubDate,

    relatedCount: relatedArticles.length,

    related: relatedArticles

  });

}

return { processedNews: result };

三、使用Loop节点实现条件循环

适用场景:需要满足特定条件才停止的循环(如重试API直到成功)

  1. 添加Loop节点并设置循环条件:

    {{ $node["API请求"].json["status"] !== "success" && 

    $json.retries < 3 }}

  2. 循环体内配置:

    • API请求节点

    • 错误处理节点

    • 重试计数更新:{{ $json.retries + 1 }}

  3. 循环完成后连接后续节点

四、实战案例:批量处理新闻数据

需求:将多条新闻按关键词分类并统计数量

// 在Code节点中处理多条新闻数据

const newsItems = $node["RSS获取"].json["items"];

const categoryStats = {

  "技术趋势": 0,

  "核心技术": 0,

  "头部企业": 0,

  "应用场景": 0,

  "其他": 0

};

// 定义关键词分类

const keywordCategories = {

  "技术趋势": ["GPT-4", "大模型", "生成式AI", "AGI", "AIGC"],

  "核心技术": ["深度学习", "神经网络", "自然语言处理", "计算机视

  觉"],

  "头部企业": ["OpenAI", "谷歌", "百度", "微软", "阿里", "腾讯

  "],

  "应用场景": ["医疗", "教育", "金融", "自动驾驶", "智能制造"]

};

// 遍历所有新闻

newsItems.forEach(news => {

  let newsCategory = "其他";

  

  // 遍历新闻关键词

  news.keywords.forEach(keyword => {

    // 匹配分类

    for(const [category, keywords] of Object.entries

    (keywordCategories)) {

      if(keywords.includes(keyword)) {

        newsCategory = category;

        categoryStats[category]++;

        return; // 找到分类后跳出循环

      }

    }

  });

  

  // 为新闻添加分类

  news.category = newsCategory;

});

return {

  totalNews: newsItems.length,

  categoryStats: categoryStats,

  processedNews: newsItems

};

五、循环处理常见问题解决

1. 避免无限循环

// 添加最大循环次数保护

const maxIterations = 100;

let count = 0;

let result = [];

let currentItem = $json.firstItem;

while(currentItem && count < maxIterations) {

  result.push(currentItem);

  currentItem = currentItem.nextItem;

  count++;

}

return { items: result, iterations: count };

2. 循环中的异步处理

// 使用Promise.all处理异步操作

async function processItems(items) {

  const promises = items.map(async (item) => {

    // 异步API调用

    const response = await fetch('https://api.example.com/

    process', {

      method: 'POST',

      body: JSON.stringify(item)

    });

    return response.json();

  });

  

  return Promise.all(promises);

}

// 执行并返回结果

const processed = await processItems($json.items);

return { processedItems: processed };

六、循环性能优化技巧

  1. 批量处理:使用Split In Batches节点控制每次处理数量

  2. 提前退出:在循环中使用break或return减少不必要迭代

  3. 避免嵌套循环:尽可能使用数组方法替代多层for循环

  4. 使用索引缓存:对频繁访问的大型数组建立索引

  5. 并行处理:在Code节点中使用Promise.all提高处理速度

这些循环处理方法可以根据实际需求灵活组合使用,建议优先尝试可视化节点(如Split In Batches),复杂场景再使用Code节点编写自定义循环逻辑。

七、使用模式的分别

⚠️注意⚠️:

以下代码语法适用于模式,即输入对象为:$json或$input.item.json

Run Once for Each: ltemRun this code as many times as there are input items

如果是下面模式,输入对象为:$input.all()

Run Once for All ltems
Run this code only once, no matter how many input items there are

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

正经教主

有钱捧个钱场,没钱捧个人场👌

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值