Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

166
Views
¿Cómo obtengo el índice de un objeto en un bucle forEach?

Intento obtener algunos datos de mi base de datos y mostrarlos en un gráfico, pero tengo problemas para mostrarlos correctamente. Quiero que el valor de x sea el índice de los datos obtenidos.

 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 answers
Answer question

0

Tal vez hacer algo como esto:

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

También tenga en cuenta que su código es potencialmente vulnerable a XSS basado en DOM si los datos provienen de un servicio web.

about 4 years ago · Juan Pablo Isaza Report

0

Puedes usar mejor el mapa. Tanto map como forEach tienen el índice como segundo parámetro

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!