javascript - 需要以不同的方式格式化对象数组

标签 javascript arrays typescript object

我有一个矩阵响应数组:

matrixArray = [
                {Responded: 1, RowName: row1, ColName: col1},
                {Responded: 2, RowName: row1, ColName: col2},
                {Responded: 0, RowName: row1, ColName: col3},
                {Responded: 0, RowName: row2, ColName: col1},
                {Responded: 0, RowName: row2, ColName: col2},
                {Responded: 1, RowName: row2, ColName: col3},
                {Responded: 1, RowName: row3, ColName: col1},
                {Responded: 0, RowName: row3, ColName: col2},
                {Responded: 1, RowName: row3, ColName: col3},
                ...
                ...
              ];

它告诉我们一行已经响应了多少次列。 我需要以下格式的上述对象数组:

matrixArray = [
                {
                  RowName: row1,
                  col1: 1,           //Here '1' is no. of times column responded
                  col2: 2,
                  col3: 0
                },
                {
                  RowName: row2,
                  col1: 0,
                  col2: 0,
                  col3: 1
                },
                {
                  RowName: row3,
                  col1: 1,
                  col2: 0,
                  col3: 1
                },
              ];

我正在为此使用 TypeScript。 谢谢。

最佳答案

您可以使用 Array.reduce Object.values 获得想要的结果:

const matrixArray = [
  {Responded: 1, RowName: 'row1', ColName: 'col1'},
  {Responded: 2, RowName: 'row1', ColName: 'col2'},
  {Responded: 0, RowName: 'row1', ColName: 'col3'},
  {Responded: 0, RowName: 'row2', ColName: 'col1'},
  {Responded: 0, RowName: 'row2', ColName: 'col2'},
  {Responded: 1, RowName: 'row2', ColName: 'col3'},
  {Responded: 1, RowName: 'row3', ColName: 'col1'},
  {Responded: 0, RowName: 'row3', ColName: 'col2'},
  {Responded: 1, RowName: 'row3', ColName: 'col3'}
];

const result = Object.values(matrixArray.reduce((result, entry) => {
  if (!(entry.RowName in result)) {
    result[entry.RowName] = {RowName: entry.RowName};
  }
  if (!(entry.ColName in result[entry.RowName])) {
    result[entry.RowName][entry.ColName] = 0;
  }
  result[entry.RowName][entry.ColName] += entry.Responded;
  return result;
}, {}));

console.log(result);

请注意,我没有在此处键入变量以使其可运行,请随意这样做,因为您使用的是 Typescript。

说明:

  • Array.reduce循环数组并构建 RowName => {RowName, col1, col2, col3}通过增加相应的 Responded 来映射(对象)每次迭代的数量),
  • Object.values然后将其转换回数组。

关于javascript - 需要以不同的方式格式化对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54275007/

相关文章:

java - 交换排序算法查询

javascript - 如何使用 Angular5/6 显示下拉菜单中选定的项目?

javascript - 如何运行 tslint.json?

javascript - 无法在 Javascript 中对数组进行排序

javascript - 语法错误: missing ; before statement on normal statement

Javascript 单击类按钮

javascript - 是否可以更改多个图像及其各自的鼠标悬停命令?

java - 将 Arrays.asList 与 int 数组一起使用

javascript - 尚未为上下文 : _. 加载 TypeScript 导出和导入模块名称使用 require([])

javascript - Android 4,如何关闭更改事件的选择面板