如何将JS对象数组转换为按Type分组的嵌套对象数组?
JavaScript数组结构转换实现方案
你可以直接用原生Array.reduce方法实现,无需引入第三方依赖,代码如下:
const convertedA = Object.values( a.reduce((groupMap, currentItem) => { // 按Type字段分组,不存在分组则先初始化 if (!groupMap[currentItem.Type]) { groupMap[currentItem.Type] = { Type: currentItem.Type, Names: [] } } // 转换字段名后加入对应分组的Names列表 groupMap[currentItem.Type].Names.push({ Firstname: currentItem.Name, Lastname: currentItem.Surname }) return groupMap }, {}) )
实现逻辑说明
- 首先通过
reduce遍历原数组,用一个临时对象存储分组结果,以Type的值作为对象的键 - 遍历过程中自动识别是否已存在对应
Type的分组,不存在则初始化分组结构 - 将原对象的
Name、Surname字段重命名为要求的Firstname、Lastname,推入对应分组的Names数组 - 最后通过
Object.values将临时存储分组的对象转换为目标数组格式
如果你习惯用lodash实现,也可以用groupBy快速完成:
// 需先引入lodash依赖 const _ = require('lodash') const convertedA = _.map(_.groupBy(a, 'Type'), (groupItems, type) => ({ Type: type, Names: groupItems.map(item => ({ Firstname: item.Name, Lastname: item.Surname })) }))
内容的提问来源于stack exchange,提问作者minsuga
相关产品推荐
相关产品推荐

