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

162
Visualizações
How do I get the index of an object in a forEach loop?

I try to fetch some data from my database and show it in a chart but I have problems to display it correctly. I want the x-value to be the index of the fetched data.

async function getBatteryset() {
    let url = '/getBatLevel.php';
    try {
        let res = await fetch(url);
        return await res.json();
    } catch (error) {
        console.log(error);
    }
}
async function renderBattData() {
    let dataset = await getBatteryset();
    let html = '<figure class="css-chart" style="--widget-size:650px;"><ul class="line-chart">';
    dataset.forEach(data => {
        let htmlSegment = `<li>
                            <div class="data-point" data-value=${data.ID} style="bottom: ${data.BatV*100}px; left: ${data}px"></div>
                        </li>`;

        html += htmlSegment;
    });
    html += '</ul></figure>'
    let container = document.querySelector('.BattChart');
    container.innerHTML = html;
}

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

0

Maybe do something like this:

dataset.forEach((data, i) => {

    const offset = 100 // choose an offset here for each element on the X axis
    
    let htmlSegment = 
        `<li>
            <div class="data-point" data-value=${data.ID} style="bottom: ${data.BatV*100}px; left: ${i * offset}px"></div>
        </li>`;

    html += htmlSegment;
});

Also please note that your code is potentially vulnerable to DOM based XSS if the data comes from a web service.

about 4 years ago · Juan Pablo Isaza Relatório

0

You can better use map. Both map and forEach have the index as second parameter

let html = `<figure class="css-chart" style="--widget-size:650px;"><ul class="line-chart">
    $(dataset.map((data,i) => `<li>
      <div class="data-point" data-value=${data.ID} style="bottom: ${data.BatV*100}px; left: ${i * offset}px"></div>
    </li>`).join("")}
  </ul></figure>`;
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