如何通过Map与Filter实现按packingLocation分组生成表格?
问题:按packingLocation分组生成独立表格
当前代码通过map遍历数据时,每个packingLocation对应的条目会生成单独的表格,需求是按packingLocation分组,每个分组(如A、B等)生成一个包含该分组所有条目的独立表格。
原代码
{categorizedDatas2[key]?.items.map((item, index) => { if (item.packingLocation == 'A') { return ( <> <Table> <TableRow> <TableCell>{item.packingLocation}</TableCell> </TableRow> <TableRow> <TableCell>{item.Name}</TableCell> </TableRow> </Table> </> ) } if (item.packingLocation == 'B') { return ( <> <Table> <TableRow> <TableCell>{item.packingLocation}</TableCell> </TableRow> <TableRow> <TableCell>{item.Name}</TableCell> </TableRow> </Table> </> ) } })}
解决方案
步骤1:提取唯一的分组标识
先从数据中提取所有不重复的packingLocation值,避免重复生成同一分组的表格:
const items = categorizedDatas2[key]?.items || []; // 利用Set去重,得到所有唯一的packingLocation const uniqueLocations = [...new Set(items.map(item => item.packingLocation))];
步骤2:遍历分组并生成对应表格
对每个唯一的分组标识,使用filter筛选出该分组下的所有数据,再统一渲染到一个表格中:
{uniqueLocations.map(location => { // 筛选当前分组的所有条目 const groupItems = items.filter(item => item.packingLocation === location); return ( <Table key={location}> {/* 分组标题行,合并列突出显示 */} <TableRow> <TableCell colSpan={2}><strong>分组:{location}</strong></TableCell> </TableRow> {/* 遍历当前分组的条目生成数据行 */} {groupItems.map((item, idx) => ( <TableRow key={idx}> <TableCell>{item.packingLocation}</TableCell> <TableCell>{item.Name}</TableCell> </TableRow> ))} </Table> ); })}
说明
- 用
Set处理数据得到唯一分组,确保每个分组只生成一个表格 - 通过
filter精准筛选对应分组的所有数据项 - 每个表格内先展示分组标题,再遍历该分组的所有条目生成数据行,实现按分组聚合展示的效果
内容的提问来源于stack exchange,提问作者Paul VI
相关产品推荐
相关产品推荐

