如何在React、HTML中合并多API数据源为表格(无外部库)
无外部库实现多API数据源合并与表格展示方案
一、数据合并的两种可行思路
三个数据源都是对应1-12月的结构化数据,我们可以基于month字段做关联合并,以下是两种无需外部库的实现方式:
1. 主数据源遍历匹配(简单直观版)
以包含endDate、expectedPrice的firstSource为基础,遍历每个元素,用Array.find()在另外两个数据源中找到对应月份的项,提取value并重命名后合并到新对象:
function combineData(first, second, third) { return first.map(item => { const secondItem = second.find(s => s.month === item.month); const thirdItem = third.find(t => t.month === item.month); return { ...item, secondSourceValue: secondItem?.value || null, // 兜底处理缺数据情况 thirdSourceValue: thirdItem?.value || null }; }); } // 调用示例 const combinedData = combineData(firstSource, secondSource, thirdSource);
这种写法逻辑简单,因为只有12条数据,find()的性能完全够用,适合快速实现。
2. 映射表预构建(性能优化版)
先把secondSource和thirdSource转成以month为键的映射对象,后续合并时直接通过键取值,避免重复遍历数组,适合数据量更大的场景:
function combineData(first, second, third) { // 把第二个数据源转成 { 月份: 值 } 的映射 const secondMap = second.reduce((acc, curr) => { acc[curr.month] = curr.value; return acc; }, {}); // 处理第三个数据源 const thirdMap = third.reduce((acc, curr) => { acc[curr.month] = curr.value; return acc; }, {}); // 遍历主数据源完成合并 return first.map(item => ({ ...item, secondSourceValue: secondMap[item.month] || null, thirdSourceValue: thirdMap[item.month] || null })); }
用reduce()构建映射表后,取值操作是O(1)的,比find()的O(n)效率更高,逻辑也更清晰。
二、合并后数据的表格展示
拿到combinedData后,直接用原生HTML表格渲染即可,以下是React环境的示例(纯JS环境可改用原生DOM操作):
function DataTable() { // 假设已完成数据合并得到combinedData const combinedData = combineData(firstSource, secondSource, thirdSource); return ( <table border="1" cellPadding="8" cellSpacing="0"> <thead> <tr> <th>月份</th> <th>截止日期</th> <th>预期价格</th> <th>第二数据源值</th> <th>第三数据源值</th> </tr> </thead> <tbody> {combinedData.map(row => ( <tr key={row.month}> <td>{row.month}</td> <td>{row.endDate}</td> <td>{row.expectedPrice}</td> <td>{row.secondSourceValue}</td> <td>{row.thirdSourceValue}</td> </tr> ))} </tbody> </table> ); }
如果是纯JS项目,可通过document.createElement创建表格元素,遍历combinedData逐个插入行和单元格,逻辑和上述示例一致。
内容的提问来源于stack exchange,提问作者Marko Marchisio
相关产品推荐
相关产品推荐

