How to add a key:value pair from the top level array to all sub-arrays

Hi n8n Community

A quick Question

Lets assume this is the data from the previous node:

[
    {
        "order_id": 12627,
        "line_items": [
            {
                "line_id": 361
            },
            {
                "line_id": 362
            },
            {
                "line_id": 363
            }
        ]
    }
]

How we using a function I can convert it to this?

[
    {
        "order_id": 12627,
        "line_items": [
            {
                "line_id": 361,
                "order_id": 12627
            },
            {
                "line_id": 362,
                "order_id": 12627
            },
            {
                "line_id": 363,
                "order_id": 12627
            }
        ]
    }
]

I need order_id from top level to be added to all sub level items of line_items array
Help please

You can use the function node below:

const { line_items, order_id } = items[0].json;

const _lineItems = []

for (const line_item of line_items) {
    _lineItems.push({
      line_id: line_item.line_id,
      order_id,
    })
}

return [
  {
    json: {
      order_id,
      line_items: _lineItems
    }
  }
]


Exampe workflow
{
  "nodes": [
    {
      "parameters": {},
      "name": "Start",
      "type": "n8n-nodes-base.start",
      "typeVersion": 1,
      "position": [
        -140,
        80
      ]
    },
    {
      "parameters": {
        "functionCode": "return [\n  {\n    json:     {\n        \"order_id\": 12627,\n        \"line_items\": [\n            {\n                \"line_id\": 361\n            },\n            {\n                \"line_id\": 362\n            },\n            {\n                \"line_id\": 363\n            }\n        ]\n    }\n  }\n]"
      },
      "name": "Function",
      "type": "n8n-nodes-base.function",
      "typeVersion": 1,
      "position": [
        150,
        80
      ],
      "notesInFlow": true,
      "notes": "Mockup data"
    },
    {
      "parameters": {
        "functionCode": "const { line_items, order_id } = items[0].json;\n\nconst _lineItems = []\n\nfor (const line_item of line_items) {\n    _lineItems.push({\n      line_id: line_item.line_id,\n      order_id,\n    })\n}\n\nreturn [\n  {\n    json: {\n      order_id,\n      line_items: _lineItems\n    }\n  }\n]\n\n\n\n"
      },
      "name": "Function1",
      "type": "n8n-nodes-base.function",
      "typeVersion": 1,
      "position": [
        370,
        80
      ]
    }
  ],
  "connections": {
    "Start": {
      "main": [
        [
          {
            "node": "Function",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Function": {
      "main": [
        [
          {
            "node": "Function1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  }
}
1 Like

@RicardoE105

Thank you it worked.