从工作流早期检索关联的项目#
每个节点输入数据中的项目都会回溯到生成该数据所依赖的前序节点中的项目。当你需要获取比上一个节点更早的关联项目时,这一机制非常有用。
要访问工作流中更早位置的关联项目,请使用 ("<节点名称>").itemMatching(currentNodeInputIndex)。
例如,考虑以下工作流:
- Customer Datastore 节点生成示例数据:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19| ``` [ { "id":"23423532", "name":"Jay Gatsby", "email":"gatsby@west-egg.com", "notes":"Keeps asking about a green light??", "country":"US", "created":"1925-04-10" }, { "id":"23423533", "name":"José Arcadio Buendía", "email":"jab@macondo.co", "notes":"Lots of people named after him. Very confusing", "country":"CO", "created":"1967-05-05" }, ... ]
---|---
2. **Edit Fields** 节点简化了这些数据:1 2 3 4 5 6 7 8 9
| ```
[
{
"name":"Jay Gatsby"
},
{
"name":"José Arcadio Buendía"
},
...
]---|--- 3. Code 节点将电子邮件地址恢复给对应的人:
1
2
3
4
5
6
7
8
9
10
11| ``` [ { "name":"Jay Gatsby", "restoreEmail":"gatsby@west-egg.com" }, { "name":"José Arcadio Buendía", "restoreEmail":"jab@macondo.co" }, ... ]
---|---
Code 节点通过以下代码实现此功能:
[JavaScript](https://docs.n8n.io/code/cookbook/builtin/itemmatching/#__tabbed_1_1)[Python](https://docs.n8n.io/code/cookbook/builtin/itemmatching/#__tabbed_1_2)1 2 3 4
| ```
for(let i=0; i<$input.all().length; i++){
$input.all()[i].json.restoreEmail = $('Customer Datastore (n8n training)').itemMatching(i).json.email;
}
return $input.all();---|---
1
2
3
4| ``` for i, item in enumerate(_input.all()): _input.all()[i].json.restoreEmail = _('Customer Datastore (n8n training)').itemMatching(i).json.email
return _input.all();
---|---
你可以从 [n8n 官网 | itemMatching 使用示例](https://n8n.io/workflows/1966-itemmatching-usage-example/) 查看并下载该示例工作流。