Merging two JSON arrays into a single structure using JavaScript in n8n

Hey folks, I’m working on an n8n workflow and I’m stuck. I’ve got two JSON arrays from the Zammad API. One contains ticket details, and the other has ticket articles. I need to merge them into a single structure for a custom NodeJS script.

The expected output should be:

{
  "Ticket": { ticket_data },
  "articles": [ article_data ]
}

I’m not too savvy with JavaScript, so I’m having trouble merging these arrays while adding the ‘Ticket’ and ‘articles’ labels. I’ve looked up some solutions for combining JSON objects, but the extra requirement keeps tripping me up. Any examples or guidance on how to craft this code in n8n would be greatly appreciated! Thanks a lot!

I’ve encountered this scenario before in n8n. Here’s a straightforward approach using the ‘Function’ node:

const mergedData = {
Ticket: items[0].json,
articles: items[1].json
};

return [{ json: mergedData }];

This assumes your ticket data is in the first item and articles in the second. Adjust if needed.

One crucial point: ensure your input data is already in JSON format. If it’s a string, you’ll need to parse it first.

This method is efficient and doesn’t require complex JavaScript knowledge. It should seamlessly integrate the two arrays into your desired structure. Let me know if you need any clarification on implementing this in your workflow.

hey there! i’ve done this before in n8n. here’s a quick way:

const result = {
Ticket: items[0].json,
articles: items[1].json
};

return [{ json: result }];

make sure ur data is JSON, not strings. if it’s strings, use JSON.parse() first. hope this helps! lmk if u need more help

I’ve actually tackled a similar problem in n8n recently. What worked for me was using the ‘Function’ node to manipulate the JSON data. Here’s a snippet that might help:

const ticketData = items[0].json;
const articlesData = items[1].json;

const mergedData = {
  Ticket: ticketData,
  articles: articlesData
};

return [{ json: mergedData }];

This assumes your ticket data is in the first item and articles in the second. You might need to adjust the indexes based on your workflow setup.

One gotcha I encountered: make sure your input data is properly parsed as JSON before it reaches this function. If it’s coming in as a string, you might need to use JSON.parse() first.

Hope this helps! Let me know if you run into any issues implementing it.