I’m working with a JavaScript-based n8n function node to handle API results from a SaaS platform. The data comes in as a big JSON blob with nested arrays. I’ve managed to handle single-level nesting okay but I’m stuck on the deeper structures.
My current code splits this into separate results:
function processItems(items) {
const output = [];
for (const item of items) {
output.push(...item.json.articles);
}
return output.map(article => ({
json: Object.fromEntries(
Object.entries(article).map(([key, value]) => [
key,
Array.isArray(value) ? value.join('\n') : value
])
)
}));
}
The problem is the deeply nested ‘indicators’ array isn’t showing up in the final output. How can I tweak this to properly handle multi-level nesting? I’m not great with JavaScript so any help would be awesome!
I’ve encountered similar challenges with nested data structures in n8n. One approach that’s worked well for me is using a combination of recursion and flattening techniques. Here’s a modified version of your code that should handle the deeper nesting:
function processItems(items) {
return items.flatMap(item =>
item.json.articles.map(article => ({
json: flattenAndJoin(article)
}))
);
}
function flattenAndJoin(obj) {
const result = {};
for (const [key, value] of Object.entries(obj)) {
if (Array.isArray(value)) {
result[key] = value.map(item =>
typeof item === 'object' ? JSON.stringify(item) : item
).join(', ');
} else if (typeof value === 'object') {
Object.assign(result, flattenAndJoin(value));
} else {
result[key] = value;
}
}
return result;
}
This should preserve the structure of your nested arrays while flattening them into strings. The ‘indicators’ array will now appear in your output as a stringified JSON object within the flattened result. Let me know if you need any clarification on how this works.
As someone who’s worked extensively with n8n and complex JSON structures, I can relate to your struggle, Ethan. One approach that’s served me well is using a recursive function with Object.entries() to handle arbitrary levels of nesting. Here’s a solution that might work for you:
function processItems(items) {
return items.flatMap(item =>
item.json.articles.map(article => ({
json: processNestedObject(article)
}))
);
}
function processNestedObject(obj) {
return Object.fromEntries(
Object.entries(obj).map(([key, value]) => [
key,
Array.isArray(value)
? value.map(v => typeof v === 'object' ? JSON.stringify(v) : v).join(', ')
: typeof value === 'object'
? JSON.stringify(value)
: value
])
);
}
This approach should handle your ‘indicators’ array and other nested structures. It converts nested objects and arrays to JSON strings, which preserves their structure while flattening the overall output. You might need to adjust the joining delimiter (', ') based on your specific needs. Give it a shot and let me know if you need any tweaks!