Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

167
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda