在工作流程的這個步驟中,您將了解 n8n 資料的結構,以及如何使用程式碼節點添加自訂 JavaScript 程式碼來執行計算。 Nathan 工作流程的下一步是從已訂購的訂單中計算兩個值:
為了計算資料並為工作流程添加更多功能,您可以使用程式碼節點,它允許您撰寫自訂 JavaScript 程式碼。
<aside> 🚀
程式碼節點模式 程式碼節點有兩種操作模式,會改變其處理資料的方式。對所有項目執行一次模式允許您從輸入清單中的所有項目累積資料。對每個項目執行一次用於添加應該對每個接收到的輸入項目執行一次的自訂 JavaScript 程式碼片段。了解更多關於如何使用程式碼節點。
</aside>
在 n8n 中,在節點之間傳遞的資料是具有以下結構的物件陣列:
[
{
// Each item has to contain a "json" property. But it can be an empty object like {}.
// Any kind of JSON data is allowed. So arrays and the data being deeply nested is fine.
json: { // The actual data n8n operates on (required)
// This data is only an example, it could be any kind of JSON data
apple: 'beets',
carrot: {
dill: 1
}
},
// Binary data of item. Most items in n8n do not contain any (optional)
binary: {
// The key-name "apple" is only an example. Any kind of key-name is possible.
apple-picture: {
data: '....', // Base64 encoded binary data (required)
mimeType: 'image/png', // Optional but should be set if possible (optional)
fileExtension: 'png', // Optional but should be set if possible (optional)
fileName: 'example.png', // Optional but should be set if possible (optional)
}
}
},
...
]
現在讓我們看看如何實作這個功能。
在您的工作流程中,添加一個程式碼節點連接到 If 節點的 false
分支。
打開程式碼節點視窗,設定這些參數:
let items = $input.all();
let totalBooked = items.length;
let bookedSum = 0;
for(let i=0; i < items.length; i++) {
bookedSum = bookedSum + items[i].json.orderPrice;
}
return [{json:{totalBooked, bookedSum}}];
注意我們回傳計算結果的格式:return [{json:{totalBooked, bookedSum}}]
<aside> 🚀
資料結構錯誤
如果您沒有使用正確的資料結構,您會收到錯誤訊息:Error: Always an Array of items has to be returned!
</aside>