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

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

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 Report

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 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!