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

如何通过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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 17:55:04