Replace multiple variables values with Function Node

I’m getting success replacing one single variable value with this code.

let url1 = $node["WooCommerce Trigger"].json["meta_data"][1]["value"];
items[0].json.url1 = url1.replace(/^(?:https?:\/\/)?(?:www\.)?/i, "").split('/')[0];
return items;

But how can I do that for url2 and url3?

and How to handle it in case ["meta_data"][2]["value"] or ["meta_data"][3]["value"] are not present?

This is actually less of an n8n related question, more a JavaScript-related one.

Anyway the solution is a loop:

let index = 0;
for (const data of $node["WooCommerce Trigger"].json["meta_data"]) {
  items[0].json[`url${index++}`] = data.value.replace(/^(?:https?:\/\/)?(?:www\.)?/i, "").split('/')[0];
}
return items;

Not sure if you skip on purpose the first value in “meta_data”, in my example I do not and iterate over all of them and so also start with url0.

Here the nodes:

{
  "nodes": [
    {
      "parameters": {
        "functionCode": "let index = 0;\nfor (const data of $node[\"WooCommerce Trigger\"].json[\"meta_data\"]) {\n  items[0].json[`url${index++}`] = data.value.replace(/^(?:https?:\\/\\/)?(?:www\\.)?/i, \"\").split('/')[0];\n}\nreturn items;\n"
      },
      "name": "Function",
      "type": "n8n-nodes-base.function",
      "typeVersion": 1,
      "position": [
        950,
        350
      ]
    },
    {
      "parameters": {
        "functionCode": "items[0].json.meta_data = [\n  {\n    value: 'https://example0.com/test0'\n  },\n  {\n    value: 'https://example1.com/test1'\n  }\n];\nreturn items;"
      },
      "name": "WooCommerce Trigger",
      "type": "n8n-nodes-base.function",
      "typeVersion": 1,
      "position": [
        750,
        350
      ]
    }
  ],
  "connections": {
    "WooCommerce Trigger": {
      "main": [
        [
          {
            "node": "Function",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}
2 Likes