Home > Net >  Is there an efficient way to show images based on a route and file name using javascript?
Is there an efficient way to show images based on a route and file name using javascript?

Time:01-17

Right now I have something like

const route = '/Images/Banner/'
const slides = [
  {
      name: "banner-01",
      url: `${route}banner-01.png`
  },
  {
      name: "banner-02",
      url: `${route}banner-02.png`
 
  },
  {
      name: "banner-03",
      url: `${route}banner-03.png`
  },
]
]

In this, I'm manually adding each image and it's properties because there are only 3 images, but i want to dynamically add them based on the quantity of images with the same name (they'll always are going to be named banner-NN).

Is there an efficient way to iterate through images with the same pattern of name ('banner-') and place them in an array of objects?

CodePudding user response:

Iterating over the indicies of a collection and then inserting the indicies into the strings is easy enough...

const route = '/Images/Banner/'
const slides = Array.from(
  { length: 3 }, // 1 to 3
  (_, i) => {
    const numStr = String(i   1).padStart(2, '0');
    return {
      name: `banner-${numStr}`,
      url: `${route}banner-${numStr}`,
    };
  }
);
console.log(slides);

CodePudding user response:

@CertainPerformance's answer is fine but it relies on Array.from which not all browsers support. Just putting my way of doing this out there

const route = "/Images/Banner/";
const slides = [];
const totalItems = 100;

for (let index = 0; index < totalItems; index  ) {
  const banner = `banner-${index.toString().length > 1 ? index : `0${index}`}`;

  slides.push({
    name: banner,
    url: `${route}${banner}.png`,
  });
}

console.log(slides);

  •  Tags:  
  • Related