我有一个矩阵响应数组:
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/