I’m having trouble with a JavaScript function in n8n. It’s supposed to process data from an API, but I can’t get it to handle nested arrays properly.
The input is a big JSON object with articles. Each article has simple fields like title and summary, but also nested arrays for tags and indicators. My current code works fine for tags, but fails for the deeply nested indicators.
This works for tags, but the indicators field comes out empty. I want to list the indicator names, separated by newlines. Any ideas on how to fix this? I’m not great with JavaScript, so I’m stuck. Thanks for any help!
I’ve run into similar issues with nested arrays in n8n before. The problem is likely that the indicators field has a more complex structure than you’re accounting for. Try logging the structure of element[key] when key is ‘indicators’ to see exactly what you’re dealing with.
Based on your description, it sounds like indicators might be an array of objects, where each object has a ‘name’ property. If that’s the case, you could modify your code like this:
This approach uses flatMap to handle potential variations in the structure. It checks if each indicator has a ‘data’ property (which might be another array), and if so, it maps over that. Otherwise, it just takes the name directly.
Remember to always validate your input data structure before processing it. n8n’s data can sometimes be unpredictable, especially when dealing with external APIs.
Your approach is on the right track, but the issue likely stems from the structure of the ‘indicators’ data. Based on your code, it seems you’re expecting a simple array of objects with a ‘name’ property. However, API responses often have more complex nested structures.
Try modifying your ‘indicators’ handling like this:
This code is more robust, handling potential variations in the data structure. It checks for a ‘data’ array within each indicator object and extracts names from there if present. It also includes some error handling to avoid issues with missing properties.
Remember to thoroughly log and inspect your input data when troubleshooting. n8n’s ‘Code’ nodes are great for adding console.log statements to examine data at different stages of your workflow.