Need help with complex array handling in n8n JavaScript node
I’m working with data from an API that returns deeply nested arrays and I can’t get my n8n function to process them properly. Single level arrays work fine but the complex nested ones are giving me empty results.
Here’s my input data structure:
{
"status": "ok",
"posts": [
{
"id": "xyz789",
"headline": "sample content goes here",
"description": "sample content description",
"category": "private",
"createdAt": "2022-03-15T10:30:00.000+00:00",
"url": "example-url-here",
"topics": [],
"keywords": [
"word1",
"word2",
"word3",
"word4"
],
"metrics": [
{
"kind": "sample metric type",
"total": 8,
"data": [
"value one",
"value two",
"value three"
],
"origin": "external"
}
]
}
]
}
My current processing code:
const output = []
for (const record of items) {
output.push.apply(output, record.json.posts)
}
return output.map(item => {
const processed = {};
for (const field of Object.keys(item)) {
if (field === 'keywords') {
processed[field] = item[field].toString().replace(/,/g, '\n');
continue;
}
if (field === 'metrics') {
processed[field] = item[field].map(entry => entry.title).toString().replace(/,/g, '\n');
continue;
}
processed[field] = typeof item[field] === 'object' ? JSON.stringify(item[field]) : item[field];
}
return { json: processed };
})
The metrics field comes out empty in my final output. How do I properly extract the nested array values so they show up correctly when I export to spreadsheets? The issue seems to be with accessing properties that don’t exist in the nested objects.