如何按某些属性值对对象数组进行分组
我有两个数组。一个包含字符串的数组,其中包含名称(可能有空格):
let companies = ['Google', 'Coca Cola', 'Jonson & Jonson'];
另一个数组包含带有人的对象:
let employees = [
{name: 'Alina', company: 'Google', id : 1},
{name: 'Vika', company: 'Coca Cola', id : 2},
{name: 'Alex', company: 'Jonson & Jonson', id : 3},
{name: 'Vlad', company: 'Google', id : 4},
{name: 'Fibi', company: 'Coca Cola', id : 5},
{name: 'Joey', company: 'Google', id : 6},
];
我的任务是按名称对这些人进行分组:
const groups = [
{'Google': [
{name: 'Alina', company: 'Google', id : 1},
{name: 'Vlad', company: 'Google', id : 4},
]},
'Jonson & Jonso': [
{name: 'Alex', company: 'Jonson & Jonson', id : 3},
]},
...
];
JavaScript 中最简单且无需额外迭代的方法是什么?
我可以使用嵌套循环,但它太复杂了。也许可以用lodash
来做?
我将非常感谢任何建议。
I have two arrays. One array with strings which contains names (which may have spaces):
let companies = ['Google', 'Coca Cola', 'Jonson & Jonson'];
And another array contains objects with people:
let employees = [
{name: 'Alina', company: 'Google', id : 1},
{name: 'Vika', company: 'Coca Cola', id : 2},
{name: 'Alex', company: 'Jonson & Jonson', id : 3},
{name: 'Vlad', company: 'Google', id : 4},
{name: 'Fibi', company: 'Coca Cola', id : 5},
{name: 'Joey', company: 'Google', id : 6},
];
My task is to group those people by names:
const groups = [
{'Google': [
{name: 'Alina', company: 'Google', id : 1},
{name: 'Vlad', company: 'Google', id : 4},
]},
'Jonson & Jonso': [
{name: 'Alex', company: 'Jonson & Jonson', id : 3},
]},
...
];
What is the simplest and without extra iterations way to this in JavaScript?
I could use a nested loop, but it would be too complicated. Maybe it's possible to do with lodash
?
I will be very grateful for any advice.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
较新的
Object.groupBy
方法可以用于此目的。The newer
Object.groupBy
method can be used for this.回到未来的答案:
数组对象上的新
group
方法尚未得到许多浏览器的支持,但很快就会出现(TC39 的第 3 阶段)并且已经在 polyfill core-js 中可用)。这将允许您直接这样做:
或者甚至:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/group
A back to the future answer:
Not yet supported by lot of browsers but will come soon (Stage 3 for TC39) and already available in polyfill core-js) is the new
group
method on the array object.This will allows you to do it directly like this:
or even:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/group
最简单的方法是:
The simplest way would be:
由于您走的是简单路线,因此时间会稍长。
Since you are going the simple route it would be slightly long.
请注意,
companys
是多余的,因为所有需要的信息都在employees
中。您正在寻找的结构可能是
Map
。您只需执行以下操作:即可获得此结果(
employee
对象中不再需要字段company
):Please notice that
companies
is redundant, as all the needed info is inemployees
.The structure that you are looking for is probably
Map
. You simply do:to get this result (field
company
won't be needed anymore inemployee
object):