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);
});
});
2
Answers
You could take a flat map approach for the outer array and a simple mapping for the inner array
If I understand you correctly, you want to use a flatMap.
This should give you an array containing all aliasses.