代码节点中的项目链接
利用n8n的项链接功能访问当前项之前的数据项。该特性在使用代码节点时尤为重要。多数节点会将每个输出项与输入项建立链接,从而形成可逆向追溯的数据项链条。如需深入了解此概念,请参阅项链接概念 。本文档重点介绍实际应用案例。
在使用代码节点时,某些情况下如果需要稍后在工作流中使用$("").item ,您需要手动提供项目链接信息。所有这些场景仅适用于当您有多个传入项目时。n8n会自动处理单个项目的链接。
这些场景适用于当您:
添加新项目:新项目未链接到任何输入。
返回新项目。
想要手动控制项目链接。
n8n的自动项目链接 处理其他场景。
要控制项目链接,请在返回数据时设置pairedItem。例如,要链接到索引为0的项目:
[
{
"json" : {
. . .
},
// The index of the input item that generated this output item
"pairedItem" : 0
}
]
pairedItem 使用示例
接收以下输入数据:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22 [
{
"id" : "23423532" ,
"name" : "Jay Gatsby"
},
{
"id" : "23423533" ,
"name" : "José Arcadio Buendía"
},
{
"id" : "23423534" ,
"name" : "Max Sendak"
},
{
"id" : "23423535" ,
"name" : "Zaphod Beeblebrox"
},
{
"id" : "23423536" ,
"name" : "Edmund Pevensie"
}
]
并使用它生成仅包含名称及一条新数据的新项目:
1
2
3
4
5
6
7
8
9
10
11
12
13
14 newItems = [];
for ( let i = 0 ; i < items . length ; i ++ ){
newItems . push (
{
"json" :
{
"name" : items [ i ]. json . name ,
"aBrandNewField" : "New data for item " + i
}
}
)
}
return newItems ;
newItems 是一个不包含 pairedItem 的条目数组。这意味着无法从这些条目追溯到生成它们的原始条目。
添加 pairedItem 对象:
1
2
3
4
5
6
7
8
9
10
11
12
13
14 newItems = [];
for ( let i = 0 ; i < items . length ; i ++ ){
newItems . push (
{
"json" :
{
"name" : items [ i ]. json . name ,
"aBrandNewField" : "New data for item " + i
},
"pairedItem" : i
}
)
}
return newItems ;
现在每个新项目都会链接到用于创建它的原始项目。