How to merge two JSON datasets into single object using JavaScript in n8n workflow

I’m working with a customer support system API that returns data in separate calls. I need help combining these JSON responses into one structured object.

First API call returns customer requests:

[
  {
    "request_id": 45,
    "department_id": 1,
    "urgency_level": 3,
    "status_id": 1,
    "company_id": null,
    "reference": "REQ-2023-001",
    "subject": "System Integration Query",
    "assigned_to": 5,
    "requester_id": 8,
    "description": null,
    "initial_response_time": "2023-03-20T09:15:22.045Z",
    "response_due": null,
    "resolution_time_minutes": 0,
    "resolution_variance": 2880,
    "closed_date": null,
    "closure_deadline": null,
    "created_timestamp": "2023-03-20T09:15:22.001Z",
    "modified_timestamp": "2023-03-22T14:30:15.789Z",
    "final_closure": null
  }
]

Second API call gets related messages:

[
  {
    "message_id": 87,
    "request_id": 45,
    "category_id": 2,
    "author_id": 8,
    "sender_email": "john.doe <[email protected]>",
    "recipient_email": "[email protected]",
    "copied_to": null,
    "message_title": "System Integration Query",
    "response_to": null,
    "thread_id": "<[email protected]>",
    "thread_hash": "9a8b7c6d5e4f3g2h1i0j",
    "parent_message": null,
    "format_type": "text/plain",
    "message_content": "Hello, I need assistance with API integration setup.",
    "is_private": false,
    "system_settings": {
      "auto_reply_enabled": true,
      "automated_response": false
    },
    "last_modified_by": 5,
    "author_user_id": 5,
    "created_timestamp": "2023-03-20T09:15:22.045Z",
    "modified_timestamp": "2023-03-20T09:15:22.045Z",
    "file_attachments": [],
    "communication_type": "email",
    "sender_role": "Customer",
    "author_email": "[email protected]",
    "modifier_email": "[email protected]"
  }
]

Target structure needed:

{
  "support_request": {
    "request_id": 45,
    "department_id": 1,
    // ... all request fields
  },
  "communications": [
    {
      "message_id": 87,
      "request_id": 45,
      // ... all message fields
    }
  ]
}

I need to write JavaScript code in my n8n workflow to combine these arrays into this nested structure. The tricky part for me is adding the wrapper keys like “support_request” and “communications”. I’m not experienced with JavaScript so any help would be great!

Had the same setup with our ticketing system last year. The async API calls in n8n tripped me up at first. Your approach works, but try the Merge node instead of JavaScript if you want to keep it simple. Run both API calls into a Merge node, then use a Set node to restructure the output. If you stick with JavaScript, make sure you’re grabbing the input data right. n8n passes data differently depending on how your nodes connect. Use console.log($input.all()) first to see what structure you’re actually getting. Watch out for timing issues too - if your second API call needs data from the first, chain them instead of running parallel. I wasted hours on what turned out to be a simple execution order problem.

I’ve hit this exact problem before - manual JSON manipulation in n8n gets ugly quick.

The real problem isn’t just merging data, it’s handling multi-step API workflows properly. You need error handling, data validation, and retry logic when APIs crap out.

Skip the custom JavaScript in n8n. Use Latenode instead - it’s way cleaner for API orchestration and has built-in data transformation tools that handle this scenario easily.

Latenode lets you:

  • Set up both API calls with proper error handling
  • Use visual mappers to structure your JSON
  • Add conditional logic for mismatched request_ids
  • Schedule or trigger however you want

I’ve built similar customer support pipelines. The visual approach saves hours of debugging compared to JavaScript code blocks.

Data transformation becomes drag-and-drop instead of coding - perfect when you’re not comfortable with JavaScript.

Check it out: https://latenode.com

The Problem:

You’re trying to combine data from two separate API calls (customer requests and related messages) into a single, nested JSON object in your n8n workflow. The challenge lies in creating the wrapper keys (“support_request” and “communications”) and structuring the data correctly within those wrappers using JavaScript.

TL;DR: The Quick Fix:

Use a Code node in n8n with the following JavaScript code to merge your API responses into the desired nested structure:

const requests = $input.first().json;
const messages = $input.all()[1].json;

const result = {
  "support_request": requests[0],
  "communications": messages
};

return [{json: result}];

Step-by-Step Guide:

  1. Add a Code Node: In your n8n workflow, add a Code (JavaScript) node after the nodes that receive the JSON responses from both API calls. Ensure that these nodes are configured to output the data as JSON.

  2. Paste the Code: Copy the JavaScript code provided above into the Code node’s editor. This code assumes that the output of your first API call (customer requests) is in $input.first().json and the second API call (messages) is in $input.all()[1].json. Double-check these input references based on how your nodes are connected.

  3. Input Data Validation (Optional, but Recommended): To make your workflow more robust, you can add validation to check if both API calls returned data successfully. Modify the code like this:

const requests = $input.first().json;
const messages = $input.all()[1].json;

// Validate data exists
if (!requests || !requests.length || !messages) {
  throw new Error('Missing required data from API calls');
}

const result = {
  "support_request": requests[0],
  "communications": messages
};

return [{json: result}];

This improved code will throw an error if either API call fails, preventing the workflow from continuing with incomplete data.

  1. Test Your Workflow: Save your changes and test the workflow. The Code node should now output a JSON object with the “support_request” and “communications” wrappers, combining the data as desired.

:mag: Common Pitfalls & What to Check Next:

  • Incorrect Input References: Double-check that $input.first().json and $input.all()[1].json correctly reference the output of your API call nodes. The order of your nodes matters here, so rearrange them if necessary. Add debug nodes before the code node to inspect the $input values.

  • API Response Format: Verify that the API calls are returning JSON arrays as expected. Unexpected data formats could break the JavaScript code. Examine the API response directly using a tool like Postman to ensure the structure aligns with the code’s assumptions.

  • Array Indexing: The code assumes that both API calls return at least one item. If they could be empty, adjust the indexing in requests[0] to handle potential errors gracefully (e.g., using requests[0] || {}).

:speech_balloon: Still running into issues? Share your (sanitized) config files, the exact command you ran, and any other relevant details. The community is here to help!

Been working with n8n for customer service automation for about two years and hit this same issue multiple times. You’re missing proper error handling and data validation before the merge.

Here’s what I learned the hard way - always validate your arrays first. APIs can return empty results or different structures without warning. Check if both datasets exist and have matching request_ids before merging.

const requests = $input.first().json;
const messages = $input.all()[1].json;

// Validate data exists
if (!requests || !requests.length || !messages) {
  throw new Error('Missing required data from API calls');
}

const requestData = requests[0];
const matchingMessages = messages.filter(msg => msg.request_id === requestData.request_id);

const merged = {
  support_request: requestData,
  communications: matchingMessages
};

return [{json: merged}];

Filtering is crucial - you’ll sometimes get messages for different requests mixed together depending on your API parameters. Also set your n8n node to “Always Output Data” in settings to handle empty results gracefully.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.