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> ); }
逻辑说明
- reduce累积处理:遍历原始数组,将数据逐步累积到临时对象
acc中,对象的key为stateId,value是对应分组的完整结构。 - 初始化分组结构:如果当前
stateId对应的分组未创建,先初始化包含stateId、state和空person数组的基础结构。 - 添加人员数据:把当前遍历到的人员信息,推入对应分组的
person数组中。 - 转换为目标数组:最后用
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
相关产品推荐
相关产品推荐

