按ID分组生成独立支付通知的JavaScript实现问题
解决方案
核心思路是先按Id对原始数据分组,将相同Id的条目聚合为一组,再为每个分组单独生成完整的支付通知(包含主题、表格、落款)。
步骤1:数据分组
使用Array.reduce()将原始数据按Id归类,把相同Id的条目放在同一个数组中:
// 示例原始数据 const rawData = [ { Id: 1, valor: 100, Descricao: "商品A" }, { Id: 1, valor: 200, Descricao: "商品B" }, { Id: 2, valor: 150, Descricao: "商品C" }, { Id: 3, valor: 300, Descricao: "商品D" }, { Id: 3, valor: 50, Descricao: "商品E" } ]; // 按Id分组,得到 { 1: [...], 2: [...], 3: [...] } 格式的对象 const groupedData = rawData.reduce((acc, item) => { const idKey = item.Id; if (!acc[idKey]) acc[idKey] = []; acc[idKey].push(item); return acc; }, {});
步骤2:渲染独立通知
编写一个生成单个支付通知的函数,接收某一组同Id的数据,返回包含主题、表格、落款的完整HTML结构,最后遍历所有分组渲染到页面:
// 生成单个支付通知的函数 function buildPaymentNotification(group) { const paymentId = group[0].Id; // 生成表格行 const tableRows = group.map(item => ` <tr> <td>${item.Descricao}</td> <td>R$ ${item.valor.toFixed(2)}</td> </tr> `).join(''); // 计算当前组的总金额 const totalAmount = group.reduce((sum, item) => sum + item.valor, 0); // 返回完整通知结构 return ` <div class="payment-alert"> <h2>支付通知 #${paymentId}</h2> <table> <thead> <tr> <th>项目描述</th> <th>金额</th> </tr> </thead> <tbody>${tableRows}</tbody> <tfoot> <tr> <td><strong>总计</strong></td> <td><strong>R$ ${totalAmount.toFixed(2)}</strong></td> </tr> </tfoot> </table> <p class="alert-footer">如有疑问,请联系我们的客服团队</p> </div> `; } // 渲染所有通知到页面容器 const container = document.getElementById('payment-notifications'); Object.values(groupedData).forEach(group => { const notification = buildPaymentNotification(group); container.insertAdjacentHTML('beforeend', notification); });
补充优化
- 样式区分:给
.payment-alert添加CSS样式(比如边框、上下外边距),让每个通知视觉上独立:
.payment-alert { border: 1px solid #eee; border-radius: 4px; padding: 16px; margin-bottom: 20px; } .payment-alert table { width: 100%; margin: 12px 0; border-collapse: collapse; } .payment-alert th, .payment-alert td { border: 1px solid #eee; padding: 8px; }
- 容错处理:如果原始数据为空,或者分组后某组没有数据,可以添加判断跳过渲染。
内容的提问来源于stack exchange,提问作者Bruno
相关产品推荐
相关产品推荐

