Skip to content Skip to sidebar Skip to footer

Json Multidimensional Array To Html Table

I have a condition that require me to make a html table using json multidimensional. This is the sample of my JSON Data let year = [ { ym : '202006', data : [ {

Solution 1:

The following snippet ignores that data is an array, because your expected output ignores it, too.

let year = [
  {
    ym : "202006",
    data : [
       {
         202007: "100", 
         202008: "100", 
         202009: "100", 
         202010: "100", 
         202011: "96.71", 
         202012: "100", 
         202101: "100", 
         202102: "96.43"
       }
    ]
  }
];

let columns = year
  .map (y => y.data)
  .flat (1)
  .map (d =>Object.keys(d))
  .flat (1)
  .sort ()
  .filter ((x, i, a) => !i || x != a[i-1]);

document.write ('<table><tdata>');
document.write ('<tr style="text-transform: uppercase">');
document.write ('<th rowspan="2">time period</th>');
document.write (`<th colspan=${columns.length}>time period data</th>`);
document.write ('</tr></tr>');
for (const c of columns) {
  document.write (`<td>${c}</td>`);
}
document.write ('</tr>');
for (const y of year) {
  document.write (`<tr><td>${y.ym}</td>`);
  for (const c of columns) {
    document.write (`<td>${y.data[0][c]}</td>`);
  }
  document.write ('</tr>');
}
document.write ('<tdata><table>');

The idea is: iterated over all your data to calculate the column list. After that iterate over the years and for each year iterate over the columns to pick the right value from the data for the column. The filter after the sort makes the sorted list unique, because the code collects all columns from all data objects.

Post a Comment for "Json Multidimensional Array To Html Table"