如何将数组中的多个对象转换为按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
相关产品推荐
相关产品推荐

