typescript 根据两个属性而不是一个属性对数组中的对象进行分组

yacmzcpb  于 2023-06-24  发布在  TypeScript
关注(0)|答案(1)|浏览(150)

我有以下类型的数组,其中包含我想分组的对象(复制为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);
mepcadol

mepcadol1#

可以修改groupByObjectKey函数以接受键数组而不是单个键。下面是一个示例,说明如何执行此操作:

const groupByObjectKeys = (users: User[], keys: string[]): any => {
    return users.reduce((rv: any, x: any) => {
        const key = keys.map(k => x[k]).join('-');
        (rv[key] = rv[key] || []).push(x);

        return rv;
    }, {});
};

const usersGroupedByLastNameAndGender = groupByObjectKeys(
    users,
    ["lastName", "gender"]
);

这将根据用户的姓氏和性别对用户进行分组,通过用分隔符(在本例中是连字符)连接指定键的值来创建一个复合键。

相关问题