我有以下类型的数组,其中包含我想分组的对象(复制为JSON):
[
{
"name": "john",
"lastName": "doe",
"gender": "male"
},
{
"name": "jane",
"lastName": "doe",
"gender": "female"
},
{
"name": "peter",
"lastName": "dickons",
"gender": "male"
},
{
"name": "eva",
"lastName": "dickons",
"gender": "female"
},
]
如果我想按姓氏对每个人进行分组,我可以使用以下代码:
const groupByObjectKey = (users: User[], key: string): any => {
return users.reduce((rv: any, x: any) => {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
const usersGroupedByLastName = groupByObjectKey(
users,
"lastName"
);
我现在怎么能做同样的事情,但使用相同的函数,并向它传递两个键,然后不仅按lastName,而且按性别对对象进行分组?
const groupByObjectKey = (users, key) => {
return users.reduce((rv, x) => {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
let users = [{
"name": "john",
"lastName": "doe",
"gender": "male"
},
{
"name": "jane",
"lastName": "doe",
"gender": "female"
},
{
"name": "peter",
"lastName": "dickons",
"gender": "male"
},
{
"name": "eva",
"lastName": "dickons",
"gender": "female"
},
];
const usersGroupedByLastName = groupByObjectKey(
users,
"lastName"
);
console.log(usersGroupedByLastName);
1条答案
按热度按时间mepcadol1#
可以修改groupByObjectKey函数以接受键数组而不是单个键。下面是一个示例,说明如何执行此操作:
这将根据用户的姓氏和性别对用户进行分组,通过用分隔符(在本例中是连字符)连接指定键的值来创建一个复合键。