Home > Enterprise >  For loop inside for loop for generating strings
For loop inside for loop for generating strings

Time:02-14

I have the following code generating an image url based on an array of objects and their properties:

for (let s = 0; s < amount; s  ) {
   console.log(projects[s].imagelocation   projects[s].images[0]); 
}  

As an example this gives me the following output:

img/EnergyGoStix-assets/GoStix1.jpg
img/Premier-assets/PremierStudios1.jpg
img/Quickstix-assets/QuickStix1.jpg
img/MotherMonster-assets/MotherMonster1.jpg
img/Stepping-assets/SteppingBooklet1.jpg

However, the images property is actually an array. This array contains multiple image sources such as GoStix1.jpg, GoStix2.jpg, etc. This number of image sources varies between the projects.

How do I create a loop within a loop that would incorporate images.length where it will first go through each project and generate all image sources, prior to moving onto the next one?

P.S - Sorry for the terrible post title, had no idea what to call this. If anyone can come up with a better one to help be more precise, please let me know so I can update it.

CodePudding user response:

Just nest the loops, and be careful to use different variable names in the initialization of each.

for (let s = 0; s < amount; s  ) {
  for (let i = 0; i < projects[s].images.length; i  ) {
    console.log(projects[s].imagelocation   projects[s].images[i]);
  }
}

CodePudding user response:

Better than another for loop would be to use an Array iteration method:

for (let s = 0; s < amount; s  ) {
  projects[s].images.forEach(image => {
      console.log(projects[s].imagelocation   image);
  });
}

CodePudding user response:

How about this?

for (let s = 0; s < amount; s  ) {
for (let y in images){
   console.log(projects[s].imagelocation   projects[s].images[y]); 
}
} 

If you want to display images array only in one console, use:

for (let s = 0; s < amount; s  ) {
   console.log(projects[s].imagelocation   [...projects[s].images]); 
}
  • Related