0

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.

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);
  });
});
3
  • 3
    Maybe look into the .map() function? It's not clear what you need to do, what your data looks like and what you want the result to be. Commented Oct 27, 2023 at 20:18
  • 1
    There is no return from a forEach it is always undefined Commented Oct 27, 2023 at 20:19
  • 3
    Pushing onto an array should have worked. Please show what you tried. Commented Oct 27, 2023 at 20:20

2 Answers 2

1

If I understand you correctly, you want to use a flatMap.

data.flatMap(brandGuideline => 
    brandGuideline.children.map(child => child.component.alias))

This should give you an array containing all aliasses.

Sign up to request clarification or add additional context in comments.

1 Comment

This reply is exactly as helpful as the one I marked 'correct.' To be fair, I marked the answer that arrived first. Thank you so much!
0

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));

2 Comments

no need for these destructurings, a simple data.flatMap(item => item.children.map(child => child.component.alias)) is shorter and way more readable.
See also my answer :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.