Так?
<div id="table-container"></div>
<style>
table, th, td {
border: 1px solid;
border-collapse: collapse;
}
</style>
<script>
function groupBy(iterable, key) {
const result = {};
for (let item of iterable) {
const itemKey = item[key] ?? '';
result[itemKey] ??= [];
result[itemKey].push(item);
}
return result;
}
function makeTableNode(groupedData, groupedByKey) {
const values = Object.values(groupedData);
const firstItem = values?.at(0)?.at(0);
const table = document.createElement('table');
if (!firstItem) {
return table;
}
// thead
const thead = document.createElement('thead');
table.appendChild(thead);
const tr = document.createElement('tr');
thead.appendChild(tr);
for (let key in firstItem) {
const th = document.createElement('th');
th.textContent = key;
tr.appendChild(th);
}
// tbody
const tbody = document.createElement('tbody');
table.appendChild(tbody);
values?.forEach(list => {
list.forEach((item, index)=> {
const tr = document.createElement('tr');
tbody.appendChild(tr);
for(let key in item) {
const isGroupByKey = key === groupedByKey;
if (index && isGroupByKey) {
continue;
}
const td = document.createElement('td');
tr.appendChild(td);
td.textContent = item[key];
if (isGroupByKey && list.length) {
td.rowSpan = list.length;
}
}
});
});
return table;
}
var data = [{id:'1',name:'1',fid:''},{id:'2',name:'2',fid:'1'} ,{id:'3',name:'3',fid:''},{id:'4',name:'4',fid:'1' },{id:'5',name:'5',fid:'3'},{id:'6',name:'6',fid:' 3'}];
(data => {
const container = document.querySelector('#table-container');
if (!container) {
return;
}
container.innerHTML = '';
container.appendChild(
makeTableNode(
groupBy(data, 'fid'),
'fid'
)
);
})(data);
</script>
|