Stack Overflow Answer for JSON to Table

https://stackoverflow.com/questions/59743704/creat-a-html-table-from-an-array/59744040#59744040

by Dayun123

HTML

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Table From JSON</title>
  <style type="text/css">
    table,
    td {
      border: 1px solid black;
    }
  </style>
</head>
<body>
  <h1>Table From JSON</h1>
  <table>
    <thead>
      <tr>
        <th>Year</th>
        <th>Total</th>
      </tr>
    </thead>
    <tbody>
      <!-- createRow inserts rows here -->
    </tbody>
</table>
  <script type="text/javascript" src="./main.js"></script>
</body>
</html>

JavaScript

const tbody = document.querySelector('tbody');

const data = [
  {
    Total: 123,
    Year: 2014,
  },
  {
    Total: 100,
    Year: 2015,
  },
  {
    Total: 200,
    Year: 2014,
  },
  {
    Total: 300,
    Year: 2015,
  },
];

const formattedData = data.reduce((acc, val) => {
  acc[val.Year] ? acc[val.Year] += val.Total : acc[val.Year] = val.Total;
  return acc;
}, {})

const createRow = (year, total) => {
  const tr = document.createElement('tr');
  const yearTd = document.createElement('td');
  const totalTd = document.createElement('td');
  yearTd.textContent = year;
  totalTd.textContent = total;
  tr.appendChild(yearTd);
  tr.appendChild(totalTd);
  tbody.appendChild(tr);
};

for (let year in formattedData) {
  createRow(year, formattedData[year])
}