Click here to Skip to main content
15,069,297 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
how i convert this foreach loop to a regular for-loop? I'm trying to change it to use regular for-loops instead of foreach.Can someone help me convert this nested loop so that it doesn't use any foreach loops? thanks.

users.forEach((user) => {
  let row = document.createElement("tr");

  Object.values(user).forEach((text) => {
    let cell = document.createElement("td");
    let textNode = document.createTextNode(text);
    cell.appendChild(textNode);
    row.appendChild(cell);
    if (user.row % 2 === 0) {
      row.style.backgroundColor = "#d4cccc";
    }
  });

  table.appendChild(row);
});



What I have tried:

<pre>users.forEach((user) => {
  let row = document.createElement("tr");

  Object.values(user).forEach((text) => {
    let cell = document.createElement("td");
    let textNode = document.createTextNode(text);
    cell.appendChild(textNode);
    row.appendChild(cell);
    if (user.row % 2 === 0) {
      row.style.backgroundColor = "#d4cccc";
    }
  });

  table.appendChild(row);
});
Posted
Updated 25-Dec-20 23:39pm

1 solution

The key to the problem is the two forEach statements. You need to check the type of the two sets, users and values, in order to iterate through them. If they are arrays then you can use the length property to limit the loops.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900