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

189
Visualizações
javascript loop wrapping every 4 elements in a parent

I have JSON object that looks similar to this,

const siteMapItems = [
{
    section: "Facts",
    pages: [
        { label: '1', link: '#' },
    ]
},  
{
    section: "Play",
    pages: [
        { label: '1', link: '#' },
    ]
},  
{
    section: "About",
    pages: [
        { label: '1', link: '#' },
    ]
},  
{
    section: "Mission",
    pages: [
        { label: '1', link: '#' },
    ]
},  
{
    section: "Contact",
    pages: [
        { label: '1', link: '#' },
    ]
},

I am wanting to loop over this object and use it to build some output, I want to create mutiple rows and have 4 entries per row, I have tried the following,

 const renderSection = (siteMapContent) => html`${siteMapContent.map((sitemapItem, index) => {
        if(index % 4) {
            section(sitemapItem, true);
        } else {
            section(sitemapItem, false);
        }

const section = (item, parent) => {
    if(parent) {
        return html`<div class="p-sitemap__row"><div class="p-site-map__column">
            <h2 class="p-site-map__section-title">${item.section}</h2>
            <ul class="p-site-map__list">
                ${renderList(item.pages)}
            </ul></div></div>`;
    }
    return html`<div class="p-site-map__column">
    <h2 class="p-site-map__section-title">${item.section}</h2>
    <ul class="p-site-map__list">
        ${renderList(item.pages)}
    </ul></div>`;
};

This creates outlike this,

enter image description here

Which as you can see wraps every 4th element in the row not creating a new row with 4 elements in it?

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

0

If you first aggregate your data into an array of arrays (with 4 items per inner array) then it will make it a lot easier to loop over and create your sections:

const siteMapItems = [{section:"Facts",pages:[{label:"1",link:"#"}]},{section:"Play",pages:[{label:"1",link:"#"}]},{section:"About",pages:[{label:"1",link:"#"}]},{section:"Mission",pages:[{label:"1",link:"#"}]},{section:"Contact",pages:[{label:"1",link:"#"}]}];

const agg = siteMapItems.reduce((acc, item, idx) => {
  acc.curr.push(item);
  if (((idx % 4) == 3 || idx == siteMapItems.length - 1)) {
    acc.result.push(acc.curr);
    acc.curr = []
  }
  return acc;
}, {
  result: [],
  curr: []
});

console.log(agg.result);
.as-console-wrapper { min-height:100% !important; }

It will become something like:

const section = (item) => {

  return html`<div class="p-sitemap__row">
                ${item.map(i => {
                      return html`<div class="p-site-map__column">
                               <h2 class="p-site-map__section-title">${i.section}</h2>
                               <ul class="p-site-map__list">
                                ${renderList(i.pages)}
                               </ul></div>`;
                      }}
              </div>`;
    
};
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