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

React中如何将数组按state分组映射为复杂对象?

按state分组数组生成目标结构的实现方案

你当前用map遍历数组的方式,会把每个原始对象单独转换为一个新对象,自然无法实现分组效果。要完成按stateId/state分组的需求,需要用Array.reduce()来累积处理数据:

修改后的代码

import "./styles.css";

export default function App() {
  
  const data = [
      {
        "id": 1,
        "name": "Chris",
        "state": "MA",
        "stateId": 1
      },
      {
        "id": 2,
        "name": "Jenna",
        "state": "MA",
        "stateId": 1
      },
      {
        "id": 3,
        "name": "Pat",
        "state": "RI",
        "stateId": 2
      },
      {
        "id": 4,
        "name": "Dan",
        "state": "RI",
        "stateId": 2
      }
    ];

  // 使用reduce进行分组处理
  const newdata = Object.values(data.reduce((acc, item) => {
    // 以stateId作为分组的唯一标识
    const key = item.stateId;
    // 如果当前分组不存在,初始化结构
    if (!acc[key]) {
      acc[key] = {
        stateId: item.stateId,
        state: item.state,
        person: []
      };
    }
    // 将当前人员信息加入对应分组的person数组
    acc[key].person.push({ id: item.id, name: item.name });
    return acc;
  }, {}));

  console.log(newdata)

  return (
    <div className="App">      
      <h1>test</h1>
    </div>
  );
}

逻辑说明

  1. reduce累积处理:遍历原始数组,将数据逐步累积到临时对象acc中,对象的key为stateId,value是对应分组的完整结构。
  2. 初始化分组结构:如果当前stateId对应的分组未创建,先初始化包含stateId、state和空person数组的基础结构。
  3. 添加人员数据:把当前遍历到的人员信息,推入对应分组的person数组中。
  4. 转换为目标数组:最后用Object.values()提取临时对象的所有value,得到你需要的数组格式。

最终输出结果

运行后newdata会和你期望的结构完全一致:

[
  {
    "stateId": 1,
    "state": "MA",
    "person": [
      {
        "id": 1,
        "name": "Chris"
      },
      {
        "id": 2,
        "name": "Jenna"
      }
    ]
  },
  {
    "stateId": 2,
    "state": "RI",
    "person": [
      {
        "id": 3,
        "name": "Pat"
      },
      {
        "id": 4,
        "name": "Dan"
      }
    ]
  }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 05:03:36