如何從輸入項目中提取單個鍵值對,進行一些更改並將其放回 Code 節點的輸出?

Hello, Everyone.

I’m struggling with processing input data in the Code node (taken from a n8n Form). I have a following input:

[

{

“Imię i nazwisko:”: “dfgdg”,

“e-mail:”: “gdg@dfdf.gdf”,

“Telefon:”: “4453453”,

“Bierzesz udział jako:”: “Firma”,

“submittedAt”: “2026-06-18T17:04:14.285+02:00”,

“formMode”: “test”

}

]

I want to check if the value of the field “Telefon:” has whitespaces and if so, to remove them, and next to put modified input to the output, with some extra fields created in the Code node. The problem I have is that I can’t put this modified input in the output of the node.

Here is my workflow, and the node I have problem with, is called “Calculate dates and NIP”.

嗨,主要問題是 Code 節點的輸出必須以包含 json 物件的項目形式返回。

另外,你不需要遍歷電話號碼來移除空格。你可以使用 replace(/\s+/g, "")

在你的 Calculate dates and NIP Code 節點中試試這個模式:

const input = $input.first().json;

const cleanedPhone = String(input["Telefon:"] ?? "").replace(/\s+/g, "");

const availableDates = Array.from({ length: 6 }, (_, offset) => {
  const dayOffset = (today) => 2 - today;
  const date = $now.plus({
    weeks: offset + 1,
    days: dayOffset(DateTime.local().weekday),
  });

  return {
    option: date.toFormat("dd.MM.yyyy"),
  };
});

const formFields = [
  {
    fieldLabel: "Wybierz termin",
    fieldType: "dropdown",
    requiredField: true,
    fieldOptions: {
      values: availableDates,
    },
  },
];

const nipInput =
  input["Bierzesz udział jako:"] === "Firma"
    ? [
        {
          fieldLabel: "Podaj NIP",
          fieldType: "text",
          requiredField: true,
        },
      ]
    : [];

return [
  {
    json: {
      ...input,
      "Telefon:": cleanedPhone,
      combinedFormFields: [...formFields, ...nipInput],
    },
  },
];

這樣可以保留你的原始表單數據,更新 Telefon:,並為下一個 Form 節點新增 combinedFormFields

有用的參考資料:n8n 資料結構文檔

1個讚

你好,Imad,

感謝你的幫助。對我來說,正確構建這個輸出物件仍然不是很明顯。你的解決方案運作得完美無缺!