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

如何将数组中的多个对象转换为按type分组的指定结构新对象?

最简洁的实现方案(基于ES2021+语法,无额外依赖)

const input = [
  { type: 'senior', schoolName: 'school-A', country: 'America' },
  { type: 'senior', schoolName: 'school-B', country: 'England' },
  { type: 'junior', schoolName: 'school-C', country: 'German' },
  { type: 'junior', schoolName: 'school-D', country: 'Italy' }, 
];

const result = input.reduce((acc, { type, country, schoolName }) => 
  (acc[type] ??= {}, acc[type][country] = schoolName, acc), 
{})

代码说明

  • 用数组原生的reduce方法做聚合遍历,初始值为空对象
  • 遍历过程中直接解构当前项的三个属性,省略额外的属性读取代码
  • 用??=空位合并赋值运算符简化分组初始化逻辑,不存在对应type分组时自动初始化为空对象
  • 用逗号表达式省略大括号和return语句,进一步压缩代码长度

如果需要兼容ES2020之前的环境,把??=替换为||=即可:

const result = input.reduce((acc, { type, country, schoolName }) => 
  (acc[type] ||= {}, acc[type][country] = schoolName, acc), 
{})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 03:45:06