Trouble processing nested arrays in n8n JavaScript function

Hey everyone! I’m having a hard time with my n8n setup. I’m trying to process data from an API that gives me a big JSON output. The problem is some of the data is in nested arrays and I can’t figure out how to handle it right.

Here’s what my data looks like:

{
  "success": true,
  "articles": [
    {
      "id": "xyz789",
      "headline": "breaking news story",
      "snippet": "a brief summary of the news.",
      "category": "general",
      "datePosted": "2023-11-15T12:30:00.000+00:00",
      "url": "https://example.com/news",
      "topics": [],
      "keywords": [
        "news",
        "update",
        "current events"
      ],
      "metadata": [
        {
          "kind": "source info",
          "total": 2,
          "items": [
            "reporter name",
            "news agency"
          ],
          "origin": "verified"
        }
      ]
    }
  ]
}

I’ve got a function that splits this into separate results, but I’m stuck on how to handle the nested arrays properly. Especially the ‘metadata’ part - it’s coming out blank in my output.

Can anyone help me figure out how to get all the nested info to show up correctly? I’m pretty new to JavaScript, so any tips would be super helpful. Thanks!

hey mate, i had a similar issue. try using a .forEach() loop to go through the nested arrays. something like:

articles.forEach(article => {
article.metadata.forEach(meta => {
// process each metadata item here
});
});

this should help ya get all the nested stuff. good luck!

I’ve encountered similar issues with nested arrays in n8n. Here’s an approach that might help:

In your JavaScript function, you’ll need to recursively iterate through the nested structures. For the ‘metadata’ array, you can use something like:

function processMetadata(metadata) {
  return metadata.map(item => ({
    kind: item.kind,
    total: item.total,
    items: item.items.join(', '),
    origin: item.origin
  }));
}

Then in your main function:

const processedData = items.map(article => ({
  ...article,
  keywords: article.keywords.join(', '),
  metadata: processMetadata(article.metadata)
}));

This should flatten the nested structures while preserving all the information. Remember to adjust the field names according to your specific needs in the output.