0

How can I generate an HTML table from an array of objects?

I have tried with below code getting object object error.

idata:[{"slot":"10:00-11:00","isBooked":false},{"slot":"11:00-12:00","isBooked":false},{"slot":"12:00-13:00","isBooked":false},{"slot":"13:00-14:00","isBooked":false},{"slot":"14:00-15:00","isBooked":false},{"slot":"15:00-16:00","isBooked":false},{"slot":"16:00-17:00","isBooked":false},{"slot":"17:00-18:00","isBooked":false},{"slot":"18:00-19:00","isBooked":false}]


<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <? var data = idata ?>
    <table>
              <tr>
              <th>Time SLOT</th>
              <th>Status</th>

          </tr>
      <? for (var i = 0; i < data.length; i++) { ?>
        <tr>
          <? for (var j = 0; j < data[i].length; j++) { ?>
            <td><?= data[i][j] ?></td>
          <? } ?>
        </tr>
      <? } ?>
    </table>
  </body>
</html>
TheMaster
  • 45,448
  • 6
  • 62
  • 85
KiKu
  • 377
  • 5
  • 22
  • Working example please so we can have a look? – CptKicks Aug 11 '20 at 18:52
  • 2
    You are treating `data[i]` as an array, but it is an object.. with for loop, either add `Object.entries(data[i])` or simply add text as `data[i].slot` and `data[i].isBooked`. – jank Aug 11 '20 at 18:58

1 Answers1

2

Simplest solution for you would be to replace for (var j = 0; j < data[i].length; j++) with for (var j in data[i])

var data =[{"slot":"10:00-11:00","isBooked":false},{"slot":"11:00-12:00","isBooked":false},{"slot":"12:00-13:00","isBooked":false},{"slot":"13:00-14:00","isBooked":false},{"slot":"14:00-15:00","isBooked":false},{"slot":"15:00-16:00","isBooked":false},{"slot":"16:00-17:00","isBooked":false},{"slot":"17:00-18:00","isBooked":false},{"slot":"18:00-19:00","isBooked":false}];

for (var i = 0; i < data.length; i++) { 
  for (var j in data[i]) { 
    console.log(data[i][j])
  }
}
ponury-kostek
  • 7,824
  • 4
  • 23
  • 31