0

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.

5
  • 1
    for (let i = 0; i < projects[s].images; i++) ? Commented Feb 13, 2022 at 15:09
  • Nested loops - search for it Commented Feb 13, 2022 at 15:09
  • for (let s = 0; s < amount; s++) { console.log(projects[s].imagelocation + for (let i = 0; i < projects[s].images; i++) { projects[s].images[i]) }; } Commented Feb 13, 2022 at 15:12
  • @VLAZ I understand the suggestion that you propose but I am not sure where to put it. Commented Feb 13, 2022 at 15:15
  • "How do I create a loop within a loop" - seems like you already know everything you need. Can you show us your attempt? Commented Feb 13, 2022 at 15:32

3 Answers 3

1

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]);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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

1 Comment

@Sean, thanks for pointing that out. I make an error, has updated it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.