gpt4 book ai didi

javascript - 使用 lodash 对对象进行分组

转载 作者:行者123 更新时间:2023-12-01 01:29:58 24 4
gpt4 key购买 nike

我有一个数组userList:

[
{email : 'abc@gmail.com',
department : 'd1'},
{email : 'abc@gmail.com',
department : 'd2'},
{email : 'dec@gmail.com',
department : 'd1'},
]

我希望它是这样的:

[
{
email : 'abc@gmail.com',
department : ['d1','d2']
},
{
email : 'dec@gmail.com',
department : ['d1']
}
]

我使用以下方法实现了它:

const userGrp = _.groupBy(userList, 'email');
let data = [];
for (let key in userGrp) {
if (userGrp.hasOwnProperty(key)) {
const obj = {
email: key,
dept: extractDept(userGrp[key]),
};
data.push(obj);
}
}

function extractDept(userObjList) {
const arr = [];
userObjList.forEach((element) => {
arr.push(element.departmentName);
});
return arr;
}

如何使用 lodash 实现它?

最佳答案

由于使用纯 js 非常容易,因此这里是根据需要进行分组的纯 js 方式

const grouped = [...foo.reduce((a, {email, department}) =>
a.set(email, (a.get(email) || []).concat(department))
, new Map)].map(([email, department]) => ({email, department}));

console.log(grouped)
<script>
const foo = [
{email : 'abc@gmail.com',
department : 'd1'},
{email : 'abc@gmail.com',
department : 'd2'},
{email : 'dec@gmail.com',
department : 'd1'},
];

</script>

关于javascript - 使用 lodash 对对象进行分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53374385/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com