gpt4 book ai didi

javascript - 使用 Lodash 映射将列表重组为按值排序的键

转载 作者:行者123 更新时间:2023-11-30 09:27:02 25 4
gpt4 key购买 nike

如果不遍历数组 3 次,我不知道该怎么做。

我希望转换一组如下所示的职位列表:

const jobs = [
{
title: 'Manager',
department: 'Retail',
location: 'New York'
},
{
title: 'Customer Service Rep',
department: 'Corporate',
location: 'Washington D.C.'
},
{
title: 'Clerk',
department: 'Retail',
location: 'New York'
},
...
];

进入具有相关工作的独特部门的对象:

const deps = {
'Corporate': [
{
title: 'Customer Service Rep',
department: 'Corporate',
location: 'Washington D.C.'
},
],
'Retail': [
{
title: 'Manager',
department: 'Retail',
location: 'New York'
},
{
title: 'Clerk',
department: 'Retail',
location: 'New York'
},
],
};

_map 是我最好的选择吗?有没有更 Eloquent 方式来做到这一点?

最佳答案

您可以使用array#reduce 根据部门 对作业进行分组。

const jobs = [ { title: 'Manager', department: 'Retail', location: 'New York' }, { title: 'Customer Service Rep', department: 'Corporate', location: 'Washington D.C.' }, { title: 'Clerk', department: 'Retail', location: 'New York' }],
deps = jobs.reduce((r,job) => {
r[job.department] = r[job.department] || [];
r[job.department].push(job);
return r;
},{});
console.log(deps);

您可以使用 _.groupBy

const jobs = [ { title: 'Manager', department: 'Retail', location: 'New York' }, { title: 'Customer Service Rep', department: 'Corporate', location: 'Washington D.C.' }, { title: 'Clerk', department: 'Retail', location: 'New York' }],
deps = _.groupBy(jobs, 'department');
console.log(deps);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>

关于javascript - 使用 Lodash 映射将列表重组为按值排序的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48772925/

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