Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

217
Visualizações
Is there an efficient way to show images based on a route and file name using javascript?

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?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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

about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda