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

如何基于现有数组对象生成指定格式的新对象?

如何将分组后的数组对象转换为指定格式?

问题背景

原始数组对象结构如下:

[
  {rYear: '1Y', rType: 'TypeA', rVal: 41},
  {rYear: '2Y', rType: 'TypeA', rVal: 11},
  {rYear: '3Y', rType: 'TypeA', rVal: 32},
  {rYear: '1Y', rType: 'TypeB', rVal: 12},
  {rYear: '2Y', rType: 'TypeB', rVal: 21},
  {rYear: '3Y', rType: 'TypeB', rVal: 16}
]

需要转换为以下格式:

[
  {rType: 'TypeA', 1Y: 41, 2Y: 11, 3Y: 32},
  {rType: 'TypeB', 1Y: 12, 2Y: 21, 3Y: 16}
]

尝试使用lodash的_.groupBy()方法后未得到预期结果,需实现上述转换逻辑。

解决方案

方法一:基于Lodash实现

_.groupBy()仅能完成按rType分组的基础操作,还需要对分组后的每组数据进行结构转换,最终提取为数组:

const _ = require('lodash');

const originalData = [
  {rYear: '1Y', rType: 'TypeA', rVal: 41},
  {rYear: '2Y', rType: 'TypeA', rVal: 11},
  {rYear: '3Y', rType: 'TypeA', rVal: 32},
  {rYear: '1Y', rType: 'TypeB', rVal: 12},
  {rYear: '2Y', rType: 'TypeB', rVal: 21},
  {rYear: '3Y', rType: 'TypeB', rVal: 16}
];

const transformedData = _.chain(originalData)
  // 按rType分组,得到以类型为键的对象
  .groupBy('rType')
  // 遍历每个分组,转换为目标结构
  .mapValues(group => {
    return group.reduce((result, item) => {
      result[item.rYear] = item.rVal;
      return result;
    }, { rType: group[0].rType });
  })
  // 提取对象的所有值,转为数组
  .values()
  .value();

console.log(transformedData);

方法二:原生JavaScript实现

无需依赖第三方库,用原生JS也可完成转换:

const originalData = [
  {rYear: '1Y', rType: 'TypeA', rVal: 41},
  {rYear: '2Y', rType: 'TypeA', rVal: 11},
  {rYear: '3Y', rType: 'TypeA', rVal: 32},
  {rYear: '1Y', rType: 'TypeB', rVal: 12},
  {rYear: '2Y', rType: 'TypeB', rVal: 21},
  {rYear: '3Y', rType: 'TypeB', rVal: 16}
];

// 第一步:按rType分组
const groupedMap = {};
originalData.forEach(item => {
  if (!groupedMap[item.rType]) {
    groupedMap[item.rType] = [];
  }
  groupedMap[item.rType].push(item);
});

// 第二步:转换每组数据为目标结构
const transformedData = Object.values(groupedMap).map(group => {
  return group.reduce((result, item) => {
    result[item.rYear] = item.rVal;
    return result;
  }, { rType: group[0].rType });
});

console.log(transformedData);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 17:15:44