Combining two distinct JSON arrays into a unified object format using JavaScript in n8n

I am currently working with a helpdesk system API that provides data in separate requests. My goal is to consolidate this information into a single format suitable for my external service.

Current Situation

I first retrieve order details:

[
  {
    "order_id": 42,
    "department_id": 1,
    "status_id": 3,
    "client_id": 15,
    "reference": "ORD-2024-001",
    "description": "Inquiry about the product from a client",
    "assigned_to": 8,
    "requester_id": 15,
    "notes": null,
    "opened_at": "2024-01-10T09:30:15.123Z",
    "due_date": null,
    "resolution_time": 0,
    "time_difference": 2880,
    "completed_at": null,
    "last_activity": "2024-01-10T14:45:22.456Z",
    "agent_contact": "2024-01-10T10:15:33.789Z",
    "client_contact": "2024-01-10T14:45:22.456Z",
    "settings": {
      "source_id": 2,
      "priority_calculation": {
        "initial_response": "2024-01-10T10:15:33.789Z",
        "updated_at": "2024-01-10T14:45:22.456Z",
        "contact_time": "2024-01-10T14:45:22.456Z",
        "level_id": 1,
        "escalation_disabled": false
      }
    },
    "modified_by": 8,
    "created_by": 8,
    "creation_date": "2024-01-10T09:30:15.067Z",
    "modification_date": "2024-01-11T08:15:44.333Z"
  }
]

Next, I fetch related messages:

[
  {
    "message_id": 85,
    "order_id": 42,
    "category_id": 2,
    "author_id": 15,
    "sender": "John Smith <[email protected]>",
    "recipient": "[email protected]",
    "subject": "Inquiry about product from client",
    "thread_id": "<[email protected]>",
    "content": "Hello, I require information regarding your services.",
    "is_private": false,
    "options": {
      "auto_reply_sent": true,
      "automated_message": false
    },
    "last_modified_by": 8,
    "author_user_id": 8,
    "timestamp": "2024-01-10T10:15:33.789Z",
    "last_update": "2024-01-10T10:15:33.789Z",
    "message_type": "email",
    "author_role": "Customer",
    "created_by_email": "[email protected]",
    "updated_by_email": "[email protected]"
  }
]

What I Require

I am looking to merge these into this structure:

{
  "OrderData": {
    "order_id": 42,
    "department_id": 1,
    // ... other order fields
  },
  "messages": [
    {
      "message_id": 85,
      "order_id": 42,
      // ... other message fields
    }
  ]
}

I need assistance in writing the JavaScript code for n8n to effectively merge these arrays with customized property names. How should I structure this correctly?

I’ve been working with API integrations like this for years. The n8n solutions work, but you’re overcomplicating something simple.

I handle this exact scenario with Latenode. No multiple nodes to juggle or input position headaches. Just two HTTP requests in sequence, then a basic function node:

const orderResponse = steps.getOrders.body;
const messagesResponse = steps.getMessages.body;

return {
  OrderData: orderResponse[0],
  messages: messagesResponse
};

Where Latenode really shines is when your helpdesk API changes or you’re handling multiple orders. It manages data flow automatically, and adding error handling or retry logic doesn’t mean rebuilding everything.

Migrated similar setups from n8n last year. The debugging alone saves me hours when APIs throw unexpected data structures at you. Better monitoring and logging come standard too.

Worth checking out: https://latenode.com

It depends on whether you’re handling multiple orders or just one. Since your example has single items in arrays, just grab the first element from each dataset.

In your n8n Code node, try this:

const orderData = $input.first().json; // assuming first input contains order array
const messagesData = $input.last().json; // assuming second input contains messages array

const result = {
  OrderData: orderData[0], // extract first order object
  messages: messagesData // keep messages as array
};

return [{ json: result }];

For multiple orders, you’ll need to group messages by order_id first. Use a reduce function to create a mapping, then loop through orders to build your final structure. Just make sure your n8n workflow sends order data as the first input and messages as the second - keeps everything consistent.

Honestly, just use object destructuring since you’re always getting single items. Destructure both arrays and rebuild the object:

const [orderItem] = $('order_node').all()[0].json;
const messagesArray = $('messages_node').all()[0].json;

return [{
  json: {
    OrderData: orderItem,
    messages: messagesArray
  }
}];

Way cleaner than filtering or complex merging when you know the structure beforehand.

Try using a Merge node before your Code node - it makes data handling way simpler. Merge both datasets first, then process them together.

const items = $input.all();
const orders = items.filter(item => item.json.order_id && !item.json.message_id);
const messages = items.filter(item => item.json.message_id);

const merged = {
  OrderData: orders[0].json,
  messages: messages.map(msg => msg.json)
};

return [{ json: merged }];

This works great when you’ve got different numbers of messages per order. The filtering separates orders from messages even if your data structure changes down the road. I’ve found this pattern way more reliable in production since it handles edge cases better than just assuming input positions.