将数组从“长”数据格式转换为“宽”格式

时间:2019-10-16 22:48:08

标签: javascript arrays

我正在尝试转换从API获取的数据,以匹配要显示以显示未来收入的表格格式。我有以下数组:

const data = [{
        director: 'Michael',
        lead: 'Jim',
        mgr: 'Dwight',
        Name: 'A',
        Month: 'Oct',
        Revenue: 2
      },{
        director: 'Michael',
        lead: 'Jim',
        mgr: 'Dwight',
        Name: 'A',
        Month: 'Nov',
        Revenue: 3
      },{
        director: 'Michael',
        lead: 'Jim',
        mgr: 'Dwight',
        Name: 'B',
        Month: 'Dec',
        Revenue: 1
      },{
        director: 'Michael',
        lead: 'Jim',
        mgr: 'Andy',
        Name: 'B',
        Month: 'Nov',
        Revenue: 4
      }]

我希望能够将数组转换为如下所示:

const data2 = [{
        director: 'Michael',
        lead: 'Jim',
        mgr: 'Dwight',
        Name: 'A',
        Oct: 2,
        Nov: 3,
        Dec: 0
      },{
        director: 'Michael',
        lead: 'Jim',
        mgr: 'Dwight',
        Name: 'B',
        Oct: 0,
        Nov: 0,
        Dec: 1
      },{
        director: 'Michael',
        lead: 'Jim',
        mgr: 'Andy',
        Name: 'B',
        Oct: 0,
        Nov: 4,
        Dec: 0
      }]

基本上,我想按前几个属性对数据进行分组,然后按月汇总给定组的收入。

我找不到可行的解决方案。有什么想法吗?谢谢!

1 个答案:

答案 0 :(得分:1)

几个Array reduce可以通过地图来实现

const data = [{
  name: 'A',
  Month: 'Oct',
  Revenue: 2
},{
  name: 'A',
  Month: 'Nov',
  Revenue: 3
},{
  name: 'B',
  Month: 'Dec',
  Revenue: 1
}];
const months = data.reduce((acc, {Month})=> (acc[Month] = 0, acc), {});
const result = Object.entries(data.reduce((acc, {name, Month, Revenue}) => {
  acc[name] = acc[name] || {};
  acc[name][Month] = Revenue;
  return acc;
}, {})).map(([name, obj]) => ({name, ...months, ...obj}));
console.log(result);