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

@RicardoE105

Thank you it worked.