javascript - 按对象数组进行分组和展平以匹配所需的格式

标签 javascript arrays group-by

我有一个像这样的对象数组:

{
 { HRProfile: 'Officer1', country: 'DEU', qty: 1 },
 { HRProfile: 'Officer1', country: 'AUT', qty: 3 },
 { HRProfile: 'Officer2', country: 'CZE', qty: 1 },
 { HRProfile: 'Officer3', country: 'DEU', qty: 1 },
 { HRProfile: 'Officer2', country: 'AUT', qty: 4 },
 { HRProfile: 'Officer1', country: 'CZE', qty: 1 },
}

我想按以下方式呈现数据:

Profile name | AUT| CZE| DEU | .... | Total
-------------------------------------------
Officer1     | 3  |  1 | 1   | ...  | 5
Officer2     | 4  |  1 | 0   | ...  | 5
Officer3     | 0  |  0 | 1   | ...  | 1

(下面的值取自“数量”字段)

我可以在 HRProfile 和国家/地区上使用 group-by 来实现与此类似的嵌套结构:

'Officer1':
{
 'DEU':
  {
  { HRProfile: 'Officer1', country: 'DEU', qty: 1 },
  ...
  },
  'AUT':
  {
  ...
  }
},
'Officer2':
{
...
}

但我仍然需要以特定的方式对其进行扁平化,以实现特定国家/地区的汇总。有什么帮助吗?或者也许有更好的方法来处理这个问题?

最佳答案

所需的输出格式对我来说仍然相当模糊,尽管下面的代码应该为您提供您正在寻找的类似表格的表示。

下面的代码将首先按 HRProfile 进行分组,并获取所有国家/地区条目,以便稍后创建一个对象数组,其中每个对象都有所需的国家/地区键、总值和 0 缺失的默认值国家。

不过,这是一种奇怪的输出格式。

const sampleData = [
 { HRProfile: 'Officer1', country: 'DEU', qty: 1 },
 { HRProfile: 'Officer1', country: 'AUT', qty: 3 },
 { HRProfile: 'Officer2', country: 'CZE', qty: 1 },
 { HRProfile: 'Officer3', country: 'DEU', qty: 1 },
 { HRProfile: 'Officer2', country: 'AUT', qty: 4 },
 { HRProfile: 'Officer1', country: 'CZE', qty: 1 },
];

let countries = {};
const grouped = sampleData.reduce((acc, next) => {
  acc[next.HRProfile] = acc[next.HRProfile] || {};
  acc[next.HRProfile][next.country] = next.qty;
  // Keep track of all the countries.
  countries[next.country] = 0;
  acc[next.HRProfile].total = (acc[next.HRProfile].total || 0) + next.qty;
  return acc;
}, {});

const tableLike = Object.entries(grouped).map(([HRProfile, data]) => {
  return Object.assign({HRProfile}, countries, data);
});

console.log(grouped);
console.log(tableLike);

关于javascript - 按对象数组进行分组和展平以匹配所需的格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56791099/

相关文章:

javascript - 使用相似且不完全相同的单词进行 Angular 过滤搜索

javascript - 忽略数组中区分大小写的输入?

c# - 按总数分组

javascript - 如何让javascript在桌面而不是移动设备上运行一个功能

javascript - 如何从 HTML 字符串中删除代码?

arrays - Arduino atmega2560代码大小

Python 提取一个新的数据框

python - 减去 Pandas 数据框

javascript - HTML5/JavaScript : Store Dynamic Variable Name and Value in localStorage

javascript - 卡住javascript中的变量值