evilgenious448
evilgenious448

Reputation: 528

For loop inside for loop for generating strings

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.

Upvotes: 0

Views: 52

Answers (3)

James
James

Reputation: 2787

How about this?

for (let s = 0; s < amount; s++) {
for (let y in  projects[s].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]); 
}

Upvotes: 1

Kevin Perry
Kevin Perry

Reputation: 541

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

Upvotes: 1

Sean
Sean

Reputation: 8067

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

Upvotes: 1

Related Questions