Home > Software engineering >  How do I get the index of an object in a forEach loop?
How do I get the index of an object in a forEach loop?

Time:06-12

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  style="--widget-size:650px;"><ul >';
    dataset.forEach(data => {
        let htmlSegment = `<li>
                            <div  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;
}

CodePudding user response:

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

CodePudding user response:

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

let html = `<figure  style="--widget-size:650px;"><ul >
    $(dataset.map((data,i) => `<li>
      <div  data-value=${data.ID} style="bottom: ${data.BatV*100}px; left: ${i * offset}px"></div>
    </li>`).join("")}
  </ul></figure>`;
  • Related