Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to Return an Array from a Nested ForEach Method?

I have been working with a data structure for days and days, and am finally getting the data I want from it using a nested forEach loop. Trouble is, I’m getting a string for each loop, so in my console. I see a long list of individual strings for each item. I need to see an array of all of the strings.

Can anyone tell me how I can change my code to achieve this result? Or am I going about it the whole wrong way? Thanks.

  data.forEach(brandGuideline => {
    brandGuideline.children.forEach(child => {
      const brandGuidelineAlias = child.component.alias;
      console.log(brandGuidelineAlias); // Long list of individual strings. Can this be an array? 
    });
  });

I have tried creating an empty array and pushing my data into it, but that didn’t work because I was inside of the forEach — so I ended up getting a huge array for each of the items. Duh.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have also tried wrapping my logic in a function and pushing the data into an array at the end, but that doesn’t work because the array is out of scope. Blah.

Here is what I had tried earlier (in answer to Barmar):

let arrayOfAliases = [];
  data.forEach(brandGuideline => {
  brandGuideline.children.forEach(child => {
  const brandGuidelineAliases = child.component.alias;
  console.log(brandGuidelineAliases); // Need to only show buttons if 
  'brand-guidelines' is part of the path.
  arrayOfAliases.push(brandGuidelineAliases);
  console.log('Alias Array: ', arrayOfAliases);
  });
});

>Solution :

You could take a flat map approach for the outer array and a simple mapping for the inner array

result = data
    .flatMap(({ children }) => children.map(({ component: { alias } }) => alias));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading