React Native中如何从旧数组生成嵌套结构的新数组?
React Native 按state字段分组生成嵌套数组
可以通过Array.prototype.reduce先按state分组,再将分组结果转换为你需要的嵌套结构数组,具体实现如下:
原始数据
const data = [ { id: 1, name: 'Mike Mii', city: 'philps', state: 'New York'}, { id: 2, name: 'Steve Jav', city: 'Square', state: 'Chicago'}, { id: 3, name: 'Jhonny', city: 'market', state: 'New York'}, { id: 4, name: 'philps', city: 'booket', state: 'Texas'}, { id: 5, name: 'smith', city: 'brookfield', state: 'Florida'}, { id: 6, name: 'Broom', city: 'old street', state: 'Florida'}, ];
实现代码
// 按state分组并整理人员信息 const groupedByState = data.reduce((acc, item) => { if (!acc[item.state]) { acc[item.state] = []; } // 生成组内自增id,提取需要的字段 acc[item.state].push({ id: acc[item.state].length + 1, name: item.name, city: item.city }); return acc; }, {}); // 转换为目标数组格式 const new_data = Object.entries(groupedByState).map(([state, people], index) => ({ id: index + 1, state, people }));
说明
- 分组阶段:使用
reduce遍历原始数组,以state作为对象的键,将同一地区的人员信息收集到对应的数组中,同时生成组内的自增ID。 - 格式转换阶段:通过
Object.entries将分组后的对象转换为键值对数组,再遍历生成外层对象,包含自增的ID、地区名称和对应的人员列表。
内容的提问来源于stack exchange,提问作者Ean Bros
相关产品推荐
相关产品推荐

