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

ReactJS中如何遍历两个数组按分组合并数据并渲染UI

React + ES6 数组合并分组实现方案

核心逻辑分两步:先基于分组数组初始化带空数据列表的聚合结构,再遍历数据列表按category字段匹配归入对应分组,全程使用ES6原生API实现,无需引入第三方工具库。

数据聚合核心代码

运行后得到的结果和你给出的期望结构完全一致:

const groupedObjects = groups.reduce((acc, group) => {
  // 按当前数据规则,分组键为分组name首字母小写,和data的category字段匹配
  // 如果后续groups新增独立编码字段(如code)直接替换此处取值逻辑即可
  const groupKey = group.name.replace(/^[A-Z]/, match => match.toLowerCase());
  acc[groupKey] = {
    id: group.id,
    name: group.name,
    array: []
  };
  return acc;
}, {});

// 遍历源数据归入对应分组
data.forEach(item => {
  // 校验分组存在性,过滤category不匹配的脏数据避免报错
  if (groupedObjects[item.category]) {
    groupedObjects[item.category].array.push(item);
  }
});

React 层渲染实现

聚合逻辑建议放在useMemo中做缓存,避免组件重渲染时重复执行计算,渲染时直接遍历聚合结果为每个分组生成独立表格即可:

import { useMemo } from 'react';

function GroupedDataTables() {
  const groupedObjects = useMemo(() => {
    const grouped = groups.reduce((acc, group) => {
      const groupKey = group.name.replace(/^[A-Z]/, match => match.toLowerCase());
      acc[groupKey] = {
        id: group.id,
        name: group.name,
        array: []
      };
      return acc;
    }, {});

    data.forEach(item => {
      if (grouped[item.category]) {
        grouped[item.category].array.push(item);
      }
    });

    return grouped;
  }, [groups, data]); // 仅当源数据变化时重新计算分组

  return (
    <div className="tables-wrapper">
      {Object.values(groupedObjects).map(group => (
        <section key={group.id} className="group-table-block">
          <h4>{group.name}</h4>
          <table border="1" cellPadding="8">
            <thead>
              <tr>
                <th>分类</th>
                <th>值名称</th>
              </tr>
            </thead>
            <tbody>
              {group.array.map((row, idx) => (
                <tr key={`${group.id}-row-${idx}`}>
                  <td>{row.category}</td>
                  <td>{row.name}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </section>
      ))}
    </div>
  );
}

实现说明

  • 聚合逻辑做了脏数据兼容,category不存在对应分组的数据会被自动过滤,不会触发脚本报错
  • useMemo依赖项严格绑定两个源数据数组,无多余计算开销
  • 渲染时所有列表项、表格行都配置了唯一key,符合React渲染diff规则,不会出现渲染异常
  • 分组匹配逻辑做了解耦,后续如果分组标识规则变更,仅需修改groupKey的取值逻辑即可,无需改动其他代码

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 00:21:49