You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用jQuery按日期合并SQL行数据生成符合预期的动态HTML表格

问题根源

  • 未做数据分组聚合:你当前是直接遍历接口返回的每一条原始数据生成表格行,没有按「日期+FreeOrPaid付费状态」做维度分组,同一个日期、同一付费属性的多条药品数据会被拆成独立行,和预期一行展示当日所有药品数量的效果不符
  • 表头与数据列映射不匹配:表头列基于ProductArray(药品短编码)的长度生成,但表格内容列是按MedIDArray(药品ID)的长度循环渲染,若两个数组长度、顺序不对应会直接导致表头和数据列错位

修正实现

核心逻辑

先将原始数据按「日期+付费状态」做分组,把同一分组下的所有药品数量存储为键值对,再遍历分组生成表格行,保证同一分组的所有药品数据在同一行展示。

代码示例

// 提取维度并去重
const ProductArray = []
const DateArray = []
const MedIDArray = []
for (var i = 0; i < count; i++) {
    ProductArray.push(Returndata[i]["ShortCode"]);
    DateArray.push(Returndata[i]["DemandDate"]);
    MedIDArray.push(Returndata[i]["MedicineID"]);
}
const uniqueProduct = ProductArray.filter(onlyUnique)
const uniqueDate = DateArray.filter(onlyUnique)
const uniqueMedId = MedIDArray.filter(onlyUnique)

// 构建分组映射:key为 日期|付费状态,value为该分组下的药品数量映射
const groupMap = {}
Returndata.forEach(item => {
    const groupKey = `${item.DemandDate}|${item.FreeOrPaid}`
    if (!groupMap[groupKey]) {
        groupMap[groupKey] = {
            date: item.DemandDate,
            freeOrPaid: item.FreeOrPaid,
            medAmount: {}
        }
    }
    groupMap[groupKey].medAmount[item.MedicineID] = item.Amount
})

// 渲染表格
let vHtml = '<table id="example_Day" class="table table-hover" cellspacing="0" width="100%">';
vHtml += '<thead>';
vHtml += '<tr id="rowDay">';
vHtml += '<th>Date</th>';
uniqueProduct.forEach(product => {
    vHtml += `<th>${product}</th>`
})
vHtml += '<th>Paid / Free</th>';
vHtml += '</tr>';
vHtml += '</thead>';
vHtml += '<tbody>';

// 遍历分组生成行
Object.values(groupMap).forEach(groupItem => {
    vHtml += '<tr>';
    vHtml += `<td>${groupItem.date}</td>`
    uniqueMedId.forEach(medId => {
        const amount = groupItem.medAmount[medId] ?? '-'
        vHtml += `<td>${amount}</td>`
    })
    vHtml += `<td>${groupItem.freeOrPaid}</td>`
    vHtml += '</tr>';
})

vHtml += '</tbody>';
vHtml += '</table>';

$('#table_day').html(vHtml);

注意:如果需要保证药品表头和数据列完全对应,建议提取去重维度时将药品ID和短编码绑定存储,避免因为数组顺序不一致导致的列错位问题。

内容的提问来源于stack exchange,提问作者Sohaib Azhar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 17:54:04