如何在角度中使用groupBy对对象进行分组
rowData = [
{code: "Machine 1", date: "2019-01-19 02:00:00", assets: { PRN: 2}},
{code: "Machine 2", date: "2019-01-20 00:00:00", assets: { PRN1: 2}},
{code: "Machine 3", date: "2019-01-21 00:00:00", assets: { PRN: 2}},
{code: "Machine 4", date: "2019-01-22 00:00:00", assets: { PRN1: 2}},
{code: "Machine 5", date: "2019-01-23 00:00:00", assets: { PRN2: 2}}
]
它是该组成对象键PRN
,PRN1
,PRN2
输出应该是
PRN: [{...}]
PRN1: [{...}]
PRN2: [{...}]
您不需要使用RxJS,因为您可以使用内置Array.reduce
函数来做到这一点。
rowData.reduce((groupedBy, row) => {
// get the PRN/PRN1/PRN2 value
const key = Object.keys(row.assets)[0];
// create an array of rows belonging to the key
// if it does not already exist
if (!Array.isArray(groupedBy[key])) {
groupedBy[key] = [];
}
// add the current row to the corresponding object key
groupedBy[key].push(row);
return groupedBy;
}, {})
结果:
{
"PRN": [
{
"code": "Machine 1",
"date": "2019-01-19 02:00:00",
"assets": {
"PRN": 2
}
},
{
"code": "Machine 3",
"date": "2019-01-21 00:00:00",
"assets": {
"PRN": 2
}
}
],
"PRN1": [
{
"code": "Machine 2",
"date": "2019-01-20 00:00:00",
"assets": {
"PRN1": 2
}
},
{
"code": "Machine 4",
"date": "2019-01-22 00:00:00",
"assets": {
"PRN1": 2
}
}
],
"PRN2": [
{
"code": "Machine 5",
"date": "2019-01-23 00:00:00",
"assets": {
"PRN2": 2
}
}
]
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句