Solucao aceita
SkyG0D 28 de fev. de 2021
Você pode fazer mais ou menos dessa maneira:
// index.html
<body>
<table data-js= "dynamic-table" ></table>
<form>
<input data-js= "input-file" type= "file" />
</form>
<script src= "dynamic-table.js" ></script>
</body>
// dynamic-tables.js
const $dynamicTable = document.querySelector('[data-js="dynamic-table"]');
const $inputFile = document.querySelector('[data-js="input-file"]');
const newTableRow = callback =>
`
<tr>
${ callback () }
</tr>
`;
const toTableHeader = header => `<th> ${ header } </th> `;
const toTableData = (header, value) => `<td> ${ value [ header ] } </td> `;
const getFormattedData = (headers, value) => newTableRow(() => headers
.map(header => toTableData(header, value))
.join("")
);
const getFormattedHeaders = headers => newTableRow(() => headers
.map(toTableHeader)
.join(""));
const getFormattedValues = (headers, values) => values
.map(value => getFormattedData(headers, value))
.join("");
const getTHead = headers =>
`
<thead>
${ getFormattedHeaders ( headers ) }
</thead>
`;
const getTBody = (headers, values) =>
`
<tbody>
${ getFormattedValues ( headers , values ) }
</tbody>
`;
const mountTable = tableData => {
const headers = Object.keys(tableData[0]);
const formattedHeaders = getTHead(headers);
const formattedValues = getTBody(headers, tableData);
$dynamicTable.innerHTML = formattedHeaders + formattedValues;
}
const handleReaderLoad = reader => () => {
const data = JSON.parse(reader.result);
mountTable(data);
}
const handleChangeFile = () => {
const isJson = $inputFile.value.endsWith ('.json');
if ($inputFile.files.length === 0 || !isJson) return;
const reader = new FileReader();
const [file] = $inputFile.files ;
reader.readAsText(file);
reader.addEventListener('load', handleReaderLoad(reader));
}
$inputFile.addEventListener ('change', handleChangeFile);
O parâmetro tableData da função mountTable deve recebe um array de objeto.
Da uma olhada no código e caso não entenda alguma parte é só falar que eu explico.
Aqui uma demonstração:
Arquivo usado para testar:
data.json (16,1,KB)