I’m working with n8n automation and getting stuck on a JavaScript problem. My workflow pulls data from an API that returns complex nested arrays, but I can’t get the deep nested parts to display properly.
Here’s what my incoming data structure looks like:
{
"status": "ok",
"posts": [
{
"id": "xyz789",
"headline": "example content goes here",
"description": "more example content here",
"category": "private",
"createdAt": "2022-03-15T09:30:00.000+00:00",
"url": "https://example_url_here",
"topics": [],
"keywords": [
"word1",
"word2",
"word3",
"word4"
],
"metrics": [
{
"name": "example metric type",
"total": 7,
"items": [
"item one",
"item two",
"item three"
],
"origin": "internal"
}
]
}
]
}
My n8n function node code looks like this:
const output = []
for (const record of items) {
output.push.apply(output, record.json.posts)
}
return output.map(item => {
const result = {};
for (const field of Object.keys(item)) {
if (field === 'keywords') {
result[field] = item[field].toString().replace(/,/g, '\n');
continue;
}
if (field === 'metrics') {
result[field] = item[field].map(entry => entry.title).toString().replace(/,/g, '\n');
continue;
}
result[field] = typeof item[field] === 'object' ? JSON.stringify(item[field]) : item[field];
}
return { json: result };
})
The problem is my metrics field comes out empty in the final output. The keywords work fine but the deeper nested metrics array doesn’t process correctly. When I export this to Google Sheets, the metrics column is blank.
How do I fix the JavaScript to handle these multi-level nested arrays properly? I’m not great with JavaScript so any help would be appreciated.