合并HTML表格中的重复JSON数据行是一个常见的数据处理需求,以下是几种高效的方法:
function mergeDuplicateRows(tableId) {
const table = document.getElementById(tableId);
const rows = table.rows;
const dataMap = new Map();
// 收集数据
for (let i = 1; i < rows.length; i++) { // 跳过表头
const cells = rows[i].cells;
const key = cells[0].textContent; // 假设第一列是唯一标识
if (!dataMap.has(key)) {
dataMap.set(key, {
row: rows[i],
count: 1,
details: Array.from(cells).map(cell => cell.textContent)
});
} else {
const existing = dataMap.get(key);
existing.count++;
// 可以在这里合并其他列的数据
}
}
// 清空表格并重新填充
while (table.rows.length > 1) table.deleteRow(1);
dataMap.forEach((value, key) => {
const newRow = table.insertRow();
value.details.forEach((detail, index) => {
const cell = newRow.insertCell(index);
cell.textContent = detail;
if (index === value.details.length - 1) { // 最后一列显示计数
cell.textContent = value.count;
}
});
});
}
function mergeDuplicateRowsJQuery(tableId) {
const $table = $(`#${tableId}`);
const mergedData = {};
$table.find('tr:gt(0)').each(function() {
const $cells = $(this).find('td');
const key = $cells.eq(0).text();
if (!mergedData[key]) {
mergedData[key] = {
cells: $cells.map((i, cell) => $(cell).text()).get(),
count: 1
};
} else {
mergedData[key].count++;
// 合并其他列数据逻辑
}
});
$table.find('tr:gt(0)').remove();
$.each(mergedData, function(key, data) {
const $row = $('<tr>');
$.each(data.cells, function(index, value) {
$row.append($('<td>').text(index === data.cells.length - 1 ? data.count : value));
});
$table.append($row);
});
}
// React示例
function MergedTable({ data }) {
const mergedData = data.reduce((acc, row) => {
const key = row.id; // 假设有id字段
if (!acc[key]) {
acc[key] = { ...row, count: 1 };
} else {
acc[key].count++;
// 合并其他字段
}
return acc;
}, {});
return (
<table>
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Count</th>
</tr>
</thead>
<tbody>
{Object.values(mergedData).map(item => (
<tr key={item.id}>
<td>{item.id}</td>
<td>{item.name}</td>
<td>{item.count}</td>
</tr>
))}
</tbody>
</table>
);
}
import _ from 'lodash';
function mergeWithLodash(data) {
return _.chain(data)
.groupBy('id') // 按id分组
.map((group) => ({
...group[0],
count: group.length,
// 合并其他需要聚合的字段
total: _.sumBy(group, 'value')
}))
.value();
}
选择哪种方法取决于你的项目架构和数据量大小。对于简单场景,纯JavaScript方案足够;复杂应用则推荐使用框架或专用库。